Answer the question
In order to leave comments, you need to log in
How to optimize the algorithm for calculating the sum of even Fibonacci numbers?
There is a task:
Each new element of the Fibonacci sequence is obtained by adding the previous two. Starting from 1 and 2, we get the first 10 elements: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... Find the sum of all even elements of the Fibonacci sequence, whose ordinal number is less than A and return the sum from the function all its numbers.
Example: A = 10
Fibonacci series: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89
Even elements: 2, 8, 34
Their sum: 44, and the sum of all its numbers is 8.
# function that find sum of digits at number
def sum_of_digits(n):
r = 0
while n:
r, n = r + n % 10, n // 10
return r
# function that find sum of even numbers in fibonacci sequence
def solution(A):
total_sum = 0
a = 1
b = 1
for i in range(0, A):
if a % 2 == 0:
total_sum += a
temporary = a
a = b
b += temporary
return sum_of_digits(total_sum)
Answer the question
In order to leave comments, you need to log in
Can be slightly optimized
def solution(A):
total_sum = 0
a = 1
b = 1
for i in range(0, A - A % 3):
temporary = a
a = b
b += temporary
total_sum = b // 2
return sum_of_digits(total_sum)
Offhand, Fibonacci numbers go in a period (odd-odd-even).
In this case, the even term is equal to the sum of the previous odd ones.
3+5 \u003d 8
13 + 21 \u003d 34
55 + 89 \u003d 144
That is, an even number is half the sum of its triple.
So we take the desired sequence, add one or two members if necessary (to get the full triple). The sum of the first 2k+1 numbers is 2*F_{2k+1}. The sum of the first 2k numbers is F_{2k+2}.
So we are looking for the sum, subtracting 1 and 2, subtracting the added terms, dividing by two, we get the answer.
We are looking for a quick search formula for the nth Fibonacci number on Wikipedia.
As a result, for any large n, the search will take almost the same time.
Another solution, slower than uvelichitel, but working and within the 4 sec limit. fit. As practice has shown, the slowest operation in this algorithm is the remainder of division by large numbers. Bitwise shifts helped to speed up the algorithm by 2 times.
def solution(A):
r = s = 0
x = y = 1
i = 2
while i < A:
y = x + y
x = y - x
n = y >> 1
n = n << 1
if n == y: # is even?
s += y
i += 1
r = sum(map(int, str(s)))
return r
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question