Skip to content

Instantly share code, notes, and snippets.

@heptat
Created February 15, 2011 04:11
Show Gist options
  • Save heptat/827085 to your computer and use it in GitHub Desktop.
Save heptat/827085 to your computer and use it in GitHub Desktop.
sum of even fibonacci numbers under 4000000
#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;
}
@heptat
Copy link
Author

heptat commented Feb 15, 2011

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