Numbers: This is the last question of Round 1A 2008. Given n, it is required to calculate the last three digits of the (3 + √ 5) ^ n integer, as shown in figureN= 5, (3 + √ 5)5 = 3935.73982, then the result should be 935. If the number is less than three digits, the value is set to zero.
(3 + √ 5) n + 1 has a recursive relationship with (3 + √ 5) n, which is expressed by an + bn √ 5 (3 + √ 5) n, then α(N + 1) = (3 + √ 5) (N + BN √ 5) = (3aN + 5bN) + (3bN +N) √ 5, which can be written as a matrix,
The Python solution code is also provided in contest analysis, as follows,
#!/usr/bin/python
#encoding:UTF-8
#Filename:Numbers.py
import sys
def matrix_mult(A, B):
C = [[0, 0], [0, 0]]
for i in range(2):
for j in range(2):
for k in range(2):
C[i][k] = (C[i][k] + A[i][j] * B[j][k]) % 1000
return C
def fast_exponentiation(A, n):
if n == 1:
return A
else:
if n % 2 == 0:
A1 = fast_exponentiation(A, n/2)
return matrix_mult(A1, A1)
else:
return matrix_mult(A, fast_exponentiation(A, n - 1))
def solveF(n):
A = [[3, 5], [1, 3]]
A_n = fast_exponentiation(A, n)
return (2 * A_n[0][0] + 999) % 1000
# return int(A_n[0][0]+A_n[1][0]*s5)%1000
inname = "input.txt"
outname = "output.txt"
if len(sys.argv)>1:
inname = sys.argv[1]
outname = inname.rstrip(".in")
outname = outname + ".out"
fin = open(inname,"r")
fout = open(outname,"w")
caseNum = 0
line = fin.readline()
testCaseNum = int(line)
lines = fin.readlines(testCaseNum)
for line in lines:
caseNum = caseNum + 1
line = line.rstrip("\n")
n = int(line)
s5 = 2.236067977
b = solveF(n)
answer = "Case #%d: " %(caseNum)
if b<100:
answer = answer + "0" + str(b)
else:
answer = answer + str(b)
answer = answer + "\n"
fout.write(answer)
fin.close()
fout.close()
The test result is that the small case test can be passed, and the result of large case is incorrect.
Another point in the Code is strange. Shouldn't an + bn √ 5 be calculated in the solver return value? Why not even √ 5?