Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Compute 2⁴⁰ mod (10⁹ + 7) by fast power in Java (long arithmetic).

Problem: Compute 2⁴⁰ mod (10⁹ + 7) by fast power in Java (long arithmetic).
static long power(long b, long e, long m) {
    long r = 1; b %= m;
    while (e > 0) {
        if ((e & 1) == 1) r = r * b % m;
        b = b * b % m;
        e >>= 1;
    }
    return r;
}
// power(2, 40, 1_000_000_007L)
What does the call return?
  1. A. 511620083
  2. B. 511627776
  3. C. 1099511627776
  4. D. 0

Correct answer: A. 511620083

Square-and-multiply keeps every intermediate below m² < 9.2 × 10¹⁸, which fits in a signed 64-bit long. 2⁴⁰ = 1 099 511 627 776 = 1099 × (10⁹ + 7) + 511 620 083. 511627776 is 2⁴⁰ mod 10⁹ (wrong modulus), and the raw value is not reduced at all. O(log e).

More Coding Interview Problems questions

Exams that ask this topic