/* 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, ... * * By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.*/ #define _POSIX_C_SOURCE 199309L #include #include #include #define N 4000000 int main(int argc, char **argv) { int fib0 = 1, fib1 = 2, fib2, sum = 2; double elapsed; struct timespec start, end; clock_gettime(CLOCK_MONOTONIC, &start); fib2 = fib0 + fib1; /* Simple brute-force approach: generate every value in the Fibonacci * sequence smaller than 4 million and if it's even add it to the total.*/ while(fib2 <= N) { if(fib2 % 2 == 0) { sum += fib2; } fib0 = fib1; fib1 = fib2; fib2 = fib0 + fib1; } clock_gettime(CLOCK_MONOTONIC, &end); elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; printf("Project Euler, Problem 2\n"); printf("Answer: %d\n", sum); printf("Elapsed time: %.9lf seconds\n", elapsed); return 0; }