[Python] Programmers - Fibonacci numbers
한국어 원문은 여기에서 볼 수 있습니다.
[Python] Programmers - Fibonacci numbers
Solution
1
2
3
4
5
6
7
def solution(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a % 1234567
F(2) = F(0) + F(1) = 0 + 1 = 1
F(3) = F(1) + F(2) = 1 + 1 = 2
F(4) = F(2) + F(3) = 1 + 2 = 3
F(5) = F(3) + F(4) = 2 + 3 = 5
Because it is added in the same way as above, it could be expressed as
a, b = b, a+b.And since the problem asks to find the remainder of dividing the nth Fibonacci number by 1234567, the return value is set to
a%1234567.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
def solution(n):
answer = 0
answer = pibo(n)
return answer
def pibo(k):
if k == 0:
return 0
elif k == 1:
return 1
else:
return pibo(k-1) + pibo(k-2)
At first, we solved it in the same way as above, but it failed in terms of efficiency because we kept recalculating the same values.