Algorithmic Toolbox__1
一、Fibonacci
inp=int(input())
def fbn(inp):
oup=[1,1]
for i in range(2,inp):
oup.append(oup[i-1]+oup[i-2])
if inp==0:
oup=0
else:
oup=oup[inp-1]
return oup
print(fbn(inp))
def get_fibonacci_last_digit_naive(n):
if n <= 1:
return n
previous = 0
current = 1
for _ in range(n - 1):
previous, current = current, previous + current
return current % 10
input = input()
n = int(input)
print(get_fibonacci_last_digit_naive(n))
def get_fibonacci_huge_naive(n, m):
if n <= 1:
return n
previous = 0
current = 1
for _ in range(n - 1):
previous, current = current, previous + current
return current % m
input = input()
n, m = map(int, input.split())
print(get_fibonacci_huge_naive(n, m))
def fibonacci_sum_naive(n):
if n <= 1:
return n
previous = 0
current = 1
sum = 1
for _ in range(n - 1):
previous, current = current%10, (previous + current)%10
sum += current%10
return sum % 10
input=input()
n = int(input)
print(fibonacci_sum_naive(n))
def fibonacci_partial_sum_naive(from_, to):
sum = 0
current = 0
next = 1
for i in range(to + 1):
if i >= from_:
sum += current
current, next = next, current + next
return sum % 10
input = input();
from_, to = map(int, input.split())
print(fibonacci_partial_sum_naive(from_, to))
def fibonacci_sum_squares_naive(n):
if n <= 1:
return n
previous = 0
current = 1
sum = 1
for _ in range(n - 1):
previous, current = current, previous + current
sum += current * current
return sum % 10
n = int(input())
print(fibonacci_sum_squares_naive(n))
二、Great Common Divisor
inp_1,inp_2=input().split(' ')
inp_1,inp_2=int(inp_1),int(inp_2)
def gcd(a,b):
if a==1 or b==1:
fin=1
return fin
else:
leap = max([a, b]) % min([a, b])
while leap != 0:
a, b = min([a, b]), leap
leap = a % b
return b
print(gcd(inp_1,inp_2))
inp_1,inp_2=input().split(' ')
inp_1,inp_2=int(inp_1),int(inp_2)
def gcd(a,b):
leap = max([a, b]) % min([a, b])
while leap != 0:
a, b = min([a, b]), leap
leap = a % b
return b
print(int(inp_1*inp_2/gcd(inp_1,inp_2)))
三、Big-o Notation
Figure out the running time of our program would be a mess because we have no idea of the system, the computer and so on. But there would be a useful notation to solve this.
In this way, we don’t care about the time that our program really takes but the scale of running time.It is said, as long as input n increase, what happen to our program’s running time.
The standard to calculate the Big-o notation is equivalent infinity----a quiet simple method we study in advanced math.In my opinion, the Big-o notation is just the value of a function with gigantic input(the calculation is just like limits in Advanced Mathematics ). It is express as O(g(n)). Even it is not very accuracy, but to compare to programs taking hundreds times longer, it is useful.