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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you're using pre-C99 version of C, use
floor()
instead ofround()
:tmp = floor(fib_n * ratio + 0.5)
fib_n = tmp + floor(tmp * ratio + 0.5);