Data Structures & AlgorithmsVery hardProduct company OA
Problem: Fibonacci numbers modulo m repeat with the Pisano period π(m). Use it to get F(10¹⁸) mod 10 without big loops.
Problem: Fibonacci numbers modulo m repeat with the Pisano period π(m). Use it to get F(10¹⁸) mod 10 without big loops.
def pisano(m):
a, b = 0, 1
for i in range(1, 6 * m + 1):
a, b = b, (a + b) % m
if a == 0 and b == 1: return i
def fib_mod(n, m):
p = pisano(m); a, b = 0, 1
for _ in range(n % p): a, b = b, (a + b) % m
return a
print(pisano(10), pisano(7), fib_mod(10**18, 10))What is printed?- A. 60 8 5
- B. 10 16 5
- C. 60 16 5
- D. 60 16 0
Correct answer: C. 60 16 5
The pair (F(i) mod m, F(i+1) mod m) can take at most m² values, so the sequence is periodic; it restarts when (0, 1) reappears (π(m) ≤ 6m). π(10) = 60 – last digits repeat every 60 terms – and π(7) = 16. 10¹⁸ mod 60 = 40, and F(40) = 102334155 ends in 5. For a single huge n, fast matrix exponentiation (O(log n)) is the alternative.
More Coding Interview Problems questions
- Problem: Compute 3^(5^20) mod p for the prime p = 10⁹ + 7. By Fermat, exponents can be reduced modulo p − 1 (since gcd(3, p) = 1). Which…
- Problem: Two equal-length strings over {x, y}; one move swaps s1[i] with s2[j] (any i, j). Minimum moves to make them equal (−1 if…
- Problem: Rabin–Karp search with a rolling hash: (a) base 10, modulus 7; (b) base 256, modulus 1000003. Count true matches and spurious…
- Problem: A primality helper tries divisors while i·i ≤ n. How many loop iterations run for n = 10⁶ and for n = 99, and what is the…
- Problem: Find the bug: version numbers stored as strings are sorted to find the smallest. What does each sort produce? python…
- Problem: What is the time complexity of this nested loop, and how many inner steps run for n = 1024? python def cnt(n): c = 0 for i in…