ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
def mat_mul(A, B, m):
    return [[sum(A[i][k] * B[k][j] for k in range(2)) % m for j in range(2)] for i in range(2)]
def fib(n, m):
    R = [[1, 0], [0, 1]]
    M = [[1, 1], [1, 0]]
    while n:
        if n & 1:
            R = mat_mul(R, M, m)
        M = mat_mul(M, M, m)
        n >>= 1
    return R[0][1]
print(fib(10, 10**9), fib(90, 10**9 + 7))
  1. A. 34 210345902
  2. B. 55 210345902
  3. C. 55 2880067194370816120
  4. D. 55 210345903

Correct answer: B. 55 210345902

Powers of the matrix [[1, 1], [1, 0]] give Fibonacci numbers, and reducing modulo m at each multiplication keeps the numbers small. F(10) = 55 is below the modulus, while F(90) = 2880067194370816120 reduces to 210345902 modulo 1000000007.

More Python Programming questions

Exams that ask this topic