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?- A. 511620083
- B. 511627776
- C. 1099511627776
- 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
- Problem: Sum the remainders of a list of signed deltas modulo 3 in C++ and in Python. cpp int a = -7 % 3; int b = 7 % -3; int c = ((-7 %…
- Problem: Sum the prices of n = 100000 items, each 50000, in Java. java int n = 100000, price = 50000; int total = n price; long total2 = n…
- Problem: Count primes below n with the sieve of Eratosthenes. python def countprimes(n): if n < 3: return 0 isp = [True] n; isp[0] =…
- Problem: Compute nCr mod p for many queries using precomputed factorials and Fermat inverses (p prime). python M = 109 + 7 N = 20 fact =…
- Problem: Find the GCD of all array elements and the LCM of a pair. cpp long long g(long long a, long long b) { return b == 0 ? a : g(b, a…
- Problem: Count trailing zeros of n! (number of factors 5). python def tz(n): c = 0 while n: n //= 5; c += n return c print(tz(25)…