Data Structures & AlgorithmsVery hardCodeforces Div2 D · matrix exponentiation
Problem: Compute F(100) mod 1000 where F(0) = 0, F(1) = 1 and F(n) = F(n-1) + F(n-2).
Problem: Compute F(100) mod 1000 where F(0) = 0, F(1) = 1 and F(n) = F(n-1) + F(n-2).
def 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 mpow(M, e, m):
R = [[1, 0], [0, 1]]
while e:
if e & 1:
R = mul(R, M, m)
M = mul(M, M, m)
e >>= 1
return R
print(mpow([[1, 1], [1, 0]], 100, 1000)[0][1])What is printed?- A. 75
- B. 175
- C. 355
- D. 25
Correct answer: A. 75
Matrix power [[1,1],[1,0]]^n holds F(n+1), F(n) in its first row, so the entry [0][1] is F(100) mod 1000. F(100) ends in 075, so the output is 75.
More Coding Interview Problems questions
- Problem: Count the inversions of the array [3, 1, 4, 1, 5, 9, 2, 6], where an inversion is a pair of positions i < j with a[i] > a[j]…
- Problem: Huffman coding is applied to symbol frequencies 5, 9, 12, 13, 16, 45, always merging the two smallest weights. What is the total…
- Problem: Find the maximum of every window of size 3 in the array below, printing the list of window maxima. python from collections import…
- Problem: Compute the Z-array (z[i] = length of the longest common prefix of s and s[i:], with z[0] set to 0) for s = 'aabxaab'. python def…
- Problem: Count the palindromic substrings of 'abacaba' (every occurrence counts, so single characters count too). python def count(s)…
- Problem: A directed graph with V vertices is relaxed with Bellman-Ford. After V - 1 full rounds of relaxing all edges, one more round…