So I\'m learning C++. I\'ve got my \"C++ Programming Language\" and \"Effective C++\" out and I\'m running through Project Euler. Problem 1...dunzo. Problem 2...not so mu
Shog9 has it right, using the type double for a problem like this is not the best way to go if you are going to cast things to ints. If your compiler supports it you should use a long long or some other 64 bit integer type, that will almost certainly hold the result of the sum of all the even terms less than 4 million of the Fibonacci sequence.
If we use the fact that the Fibonacci sequence follows the pattern odd odd even odd odd even... something as follows should do the trick.
...
unsigned int fib[3];
fib[0]=1;
fib[1]=1;
fib[2]=2;
unsigned long long sum=0;
while(fib[2]<4000000)
{
sum+=fib[2];
fib[0]=(fib[1]+fib[2]);
fib[1]=(fib[2]+fib[0]);
fib[2]=(fib[0]+fib[1]);
}
std::cout<<"The sum is: "<
that should do the trick, there might be even faster ways but this one is pretty direct and easy to read.
Looking at it I realize that you could probably get away with a standard unsigned 32 bit integer as the sum number but I will leave it as is just in case.
Additionally your code makes a large number of function calls to the generate nth Fibonacci number function. A decent optimizing compiler will inline these calls but if it doesn't then things will slow down since function calls are more expensive than other techniques.