Write a program that take command-line argument n and prints a table of the power of 2 that are less or equal to 2^n

Joined
Jul 4, 2023
Messages
370
Reaction score
41
Over here: "Highest power of 2 less than or equal to given number" you can find a very similar task.
The examples are written in programming languages as seen below

1715960813704.png


for example, in python it may look like below
Python:
def generate_powers_of_two(n):
    # Generates an array of powers of 2 to 2^n
    return [2**i for i in range(n + 1)]

if __name__ == "__main__":
    while True:
        try:
            n = int(input("Enter a number <n>: "))
            if n < 0: raise ValueError
            break
        except ValueError:
            print("The argument <n> must be a non-negative integer.")

    print(f"Powers of 2 less than or equal to 2^{n}:")
    print(generate_powers_of_two(n))

    input("\nPress ENTER to exit.")

or shell scripting
Code:
@echo off
setlocal enabledelayedexpansion

:input
set /p n="Enter a number <n>:"
if %n% lss 0 (
    echo The argument <n> must be a non-negative integer.
    goto input
)

set power=1

echo Powers of 2 less than or equal to "2^%n%":

for /L %%i in (0,1,%n%) do (
    echo !power!
    set /a power=power*2
)

echo.
pause
 
Last edited:

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,270
Latest member
TopCryptoTwitterChannels_

Latest Threads

Top