Program of the Day #7

Write a program that takes a single positive integer, \(n\) as a command line argument, and outputs the number of digits in the binary representation of \(n\). For example, recall that 14 can be written as 1x8 + 1x4 + 1x2 + 0x1, or in binary as 1110. Since this representation has 4 digits, the program should output 4 when given 14 as input. Hint: because each binary digit represents a power of two, the number of binary digits is the number of times you can divide \(n\) by 2 (using integer division) before it becomes zero.

```
>>> %Run P07_binarydigits.py 15
4
>>> 
```

Other Practice Problems

  1. Write a program that prompts the user for a positive integer \(p\) and prints the powers of 2 up to \(2^p\).

    Enter a power: 4
    2^0: 1
    2^1: 2
    2^2: 4
    2^3: 8
    2^4: 16
  2. Write a program that prompts the user for a positive integer \(n\) and prints the powers of 2 less than \(n\).

    Enter a number: 9
    2^0: 1
    2^1: 2
    2^2: 4
    2^3: 8
  3. Write a program that prompts the user until they enter the a secret password correctly. For this problem, the secret password can be whatever you want and should be hard-coded into the program. For example, if I chose "banana" as the secret password, a run of the program might look like this:

    Enter the password: algebra
    Incorrect, try again: bookend
    Incorrect, try again: banana
    You're in!
  4. Write a program that repeatedly prompts a user for positive numbers until a negative number is entered, then print the sum of the positive numbers entered (be sure not to include the negative number in the sum).

    Enter a number: 4
    Enter a number: 8
    Enter a number: 3
    Enter a number: -9
    The positive numbers entered sum to 15
  5. Write a program that prints a multiplication table for all possible combinations of the numbers 1 through 6. Ideally, print spaces as needed to pad out single-digit numbers so the table’s columns line up neatly.

    1  2  3  4  5  6
    2  4  6  8 10 12
    3  6  9 12 15 18
    4  8 12 16 20 24
    5 10 15 20 25 30
    6 12 18 24 30 36
  6. (*) Write a program that prompts the user for a positive integer and prints the binary representation of that integer, with no leading zeros.

    Enter a positive integer: 65
    65 in binary is 1000001