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?
  1. A. 60 8 5
  2. B. 10 16 5
  3. C. 60 16 5
  4. 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

Exams that ask this topic