Program of the Day #4

Write a program to extract the \(10^k\)s digit from a number \(n\), given \(k\) and \(n\). Assume \(k\) and \(n\) are both positive integers, and \(n\) has at least \(k+1\) digits. For example, to extract the 100’s digit from 1531 we’d run our program with \(n=1531\) and \(k=2\) (because \(10^2\) is 100). Hint: try using modulus and integer divison together - for example, notice that the 100’s digit of 3624 can be calculated as 3624 // 100 % 10. A couple example runs are given below:

>>> %Run P04_extract_digit.py 1531 2
The 100s digit of 1531 is 5
>>> %Run P04_extract_digit.py 13 0
The 1s digit of 13 is 3

Other Practice Problems

  1. Write a program that prints the table of powers of two as in the example below. Use one print call per line and use the sep keyword argument.

    2^0:   1
    2^1:   2
    2^2:   4
    2^3:   8
    2^4:  16
    2^5:  32
    2^6:  64
    2^7: 128
  2. Suppose a variable p contains a positive integer. Write a Python expression that evaluates to a string containing the binary representation of \(2^p - 1\) with no leading zeros. For example: if p = 3, you’d give the binary for \(2^3 - 1 = 7\), which comes out to 111. Hint: work out a couple more examples with different values of \(p\) and see if you can find a pattern.

  3. Typically, integers are stored on computers by default using 64 bits. What’s the largest integer that can be represented using 64 bits? I recommend using a calculator (or Python!) for this one.

  4. (*) Integers can be negative, but computer memory can’t store “+” and “-” signs, only 0s and 1s. For this reason, the decimal-to-binary integer conversion approach I presented doesn’t have any way to represent negative integers. Can you come up with an approach to represent both negative and positive integers using binary?