Created
February 15, 2011 04:11
-
-
Save heptat/827085 to your computer and use it in GitHub Desktop.
sum of even fibonacci numbers under 4000000
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <math.h> | |
int main(void) { | |
int N = 4000000; | |
double ratio = 1.61803399; | |
int n; | |
int sum = 0; | |
double tmp = 0.0; | |
double fib_n = 0.0; | |
for (n = 3; fib_n < N; n += 3) { | |
if (n == 3) { | |
fib_n = 2; | |
} else { | |
tmp = round(fib_n * ratio); | |
fib_n = tmp + round(tmp * ratio); | |
} | |
printf("fib_%d = %.0f\n", n, fib_n); | |
if (fib_n < N) { | |
sum += fib_n; | |
} | |
} | |
printf("sum = %d\n", sum); | |
return 0; | |
} |
If you're using pre-C99 version of C, usefloor()
instead of round()
:
tmp = floor(fib_n * ratio + 0.5)
fib_n = tmp + floor(tmp * ratio + 0.5);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
13 iterations instead of 36 which is not much of a saving.
Some fiddly stuff to try to minimise rounding error.
Golden ratio of 1.615 is not accurate enough and products occasional incorrect value.
Result:
fib_3 = 2
fib_6 = 8
fib_9 = 34
fib_12 = 144
fib_15 = 610
fib_18 = 2584
fib_21 = 10946
fib_24 = 46368
fib_27 = 196418
fib_30 = 832040
fib_33 = 3524578
fib_36 = 14930352
sum = 4613732