Function 1: Reads a positive integer number and counts the number of bits in its
ID: 3561300 • Letter: F
Question
Function 1: Reads a positive integer number and counts the number of bits in its * binary representation (as an unsigned integer), not including the leading zeros. Function 2: Reads positive integer numbers n and m and quickly computes the * value of the remainder 2^n (2 to power n) mod m.
Hint. Use this property: (a^n) mod m = (a * a * a *...* a) mod m =
= (...(((((a mod m) * a) mod m) * a) mod m) *...* a) mod m.
For instance,
(2^4) mod 7 = (2 * 2 * 2 * 2) mod 7 =
= ((((((2 mod 7) * 2) mod 7) * 2) mod 7) * 2) mod 7 =
= (((((2 * 2) mod 7) * 2) mod 7) * 2) mod 7 =
= ((((4 mod 7) * 2) mod 7) * 2) mod 7 =
= (((4 * 2) mod 7) * 2) mod 7 =
= (1 * 2) mod 7 =
= 2 mod 7 = 2.
In order to avoid overflow, you may use this property:
(a * 2) mod m = a * 2 if a < m/2,
(a * 2) mod m = (a - m) + a if a >= m/2.
This way you compute
(((4 * 2) mod 7) * 2) mod 7 = (((4 - 7) + 4) * 2) mod 7 = (1 * 2) mod 7 without use of numbers greater than 7.