PY
py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
'''
From Jan's clever len limiting solution using pop(0). Simplified some more by eliminating len check, iterating to off-by-one and returning the final result by doing the final calculation off-loop in the return statement. No extra conditonal checking needed.
'''
def f(n):
#base case
if n==0 or n==1:
return 1
#keep arr len minimal (2 or 3)
arr = [1,1]
#iterate to off-by-one (n instead of n+1)
for i in range(2,n):
arr.append((arr[-1]**2 + arr[-2]**2) % 47)
#trim arr
arr.pop(0)
#calculate the final value in return statement
return (arr[-1]**2 + arr[-2]**2)%47
# big n test. Just under Sololearn's timeout limit...
print('f({4_000_000}) =', f(4_000_000))
# test for n=0 to 50
num = 50
for i in range(num+1):
print(f'f({i}) = {f(i)}')
Enter to Rename, Shift+Enter to Preview
OUTPUT
Run