Google code jam exercise -- Numbers

Source: Internet
Author: User

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?

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.