Answer the question
In order to leave comments, you need to log in
What do you think of this solution to the problem?
I decided to take up the tasks of the Euler project. And on the second task, I got into a stupor,
because I immediately threw away the solution with the enumeration of all fibonacci numbers.
1, 1, 2 , 3, 5, 8 , 13, 21, 34 , 55, 89, 144
Looking at the sequence, I realized that every even number can be calculated.
An even fibonacci number is equal to the sum of the previous even number of the sequence multiplied by 4
and the previous even number:
34 = 8 * 4 + 2
144 = 34 * 4 + 8
Based on this, I significantly accelerated the speed of the script, since it was no longer necessary for me to list
odd numbers . The script itself:
# n и b - это первые четные 2 числа фибоначчи
n = 2
b = 8
sum_of_numbers = 0
while True:
# Здесь я задаю меньшей переменной значение следующего числа
if n < b:
n = 4 * max(n, b) + min(n, b)
else:
b = 4 * max(n, b) + min(n, b)
sum_of_numbers += max(n, b)
if max(n, b) >= 4000000:
break
# Прибавляю 10, так как изначально опустил первые 2 четных значения, и минусую последнее четное число,
# так как оно больше 4000000
print((sum_of_numbers + 10) - max(n, b))
Answer the question
In order to leave comments, you need to log in
It would be good to prove your identity.
But, so there are fibbonacci numbers that do not exceed 4,000,000. God forbid, there are 100 of them. There you can count them all several times - you can’t measure the difference in the speed of the script in any way.
As for the code: your analysis of cases, what's more - is very strange. The code is hard to read and several times slower than it could be due to the constant max and min calls. Maybe even slower than just calculating fibbonacci numbers without skipping odd ones.
Get a third temporary variable and count through it so that n is always a large number ( m = 4*n+b; b=n; n=m
) in the loop. Or generally use python chips and do multiple assignment:
b, n = n, 4*n+b;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question