1. 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

2. It looks like you forgot to increment index1. You might want to use a for loop instead to make it more obvious.

3. 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;
}```

4. is this algorithm correct ?
No, since you need to control the loop correctly.

5. ??? what do you mean is the loop still controlled in corecctly ?

6. 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.

7. oh thanks < 30 worked

thanks laserlight FTW

8. 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.

Popular pages Recent additions