Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Find the sum of all the even-valued terms in the sequence which do not exceed four million.
The Fibonacci sequence is a recursive sequence. Let's keep generating the sequence terms (starting with 0,1) and only add the even terms to our running total.
def f1(n, s0=0, s1=1): total = 0 while s1 < n: s1 = s1+s0 s0 = s1-s0 if s1%2 is 0: total += s1 return total
Surprise: this yields the correct answer. I was interested in the efficiency of the "evenness" test. Specifically, which is quicker: checking if n mod 2 is 0 or checking if n bitwise-and 0x1 is 1. Turns out, the modulo calculation is reliably quicker, though not by much.
On my set-up, f1(4e6) returns in about 1.0002e-05 seconds. Using the bitwise operation instead of the modulo check returns in about 1.0090e-5 seconds.

No comments:
Post a Comment