# program hogs

Printable View

• 02-28-2008
manzoor
program hogs
I solving the problems at Project Euler

I'm at problem 2

and I have made this program so far

but I dont know why it takes too much time to give me the answer
even if the fibonacci number is 4

the code is this

Code:

```#include <iostream> using namespace std; int main () {         typedef unsigned long ul;         ul n1 = 0;         ul n2 = 1;         ul n3;         ul index1 = 0;         long double sum = 0;         while (index1 < 4) {                 n3 = n1 + n2;                 if ( n3 % 2 == 0 ) { sum += n3; }                 n1 = n2;                 n2 = n3;         }         cout << sum;         return EXIT_SUCCESS; }```
any hint on how to improve would be really appreciated

thanks
• 02-28-2008
laserlight
It looks like you forgot to increment index1. You might want to use a for loop instead to make it more obvious.
• 02-28-2008
manzoor
thanks and is this algorithm correct ?

i have to find the solution for this
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, ...

Find the sum of all the even-valued terms in the sequence which do not exceed one million.

here's the new code

Code:

```#include <iostream> using namespace std; int main () {         typedef long double ul;         ul n1 = 0;         ul n2 = 1;         unsigned long n3;         ul sum = 0;         for (ul index = 0; index < 1000000; index++) {             n3 = n1 + n2;             if ((n3 &#37; 2) == 0 ) { sum += n3; }             n1 = n2;             n2 = n3;         }         cout << fixed << sum;         return EXIT_SUCCESS; }```
• 02-28-2008
laserlight
Quote:

is this algorithm correct ?
No, since you need to control the loop correctly.
• 02-28-2008
manzoor
??? what do you mean is the loop still controlled in corecctly ?
• 02-28-2008
laserlight
Oh, so you updated your post.

Well, you need to keep looping until you reach the largest even valued term less than a million. At the moment your loop loops a million times, which is different.
• 02-28-2008
manzoor
oh thanks < 30 worked

thanks laserlight FTW
• 02-28-2008
anon
Although it may work, it is not an entirely correct solution. What would you do, if you were required to find the sum of even fibonacci numbers up to 2 000 000. Or a user-input value?

You should not be looping a certain number of times, but as long - for example - n2 meets certain conditions.