edit:
1. problem lies on the fact that you used LESS THAN OR EQUALS TO. remember, that even if the sum reaches 2,170,389, because it is EQUALS to the condition, the condition is true, and process runs again and adds up again to exceed 4 million. get it? try removing the equals sign, and i think it should work :/
2. your solution calculates the
sum of
sum of fibonacci numbers, divisible by 3 and 5. you check if the sum is divisible by 3 and 5, not the fibonacci number.
the question needs
sum of, fibonacci numbers divisible by 3 and 5.
--
i have another way to deal with this. well, bear with me as i have little to no knowledge of fibonacci numbers XD just wiki-ed it recently :P
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
//initialize n as 0
n=0;
do {
//find fibonacci number, result is stored into F_n
F_n=...;
//if divisible by 3 or 5
if (F_n%3==0 || F_n%5==0)
{
//we first store the previous sum into somewhere
previous_sum = sum_of_fibonacci_number;
//then we add the NEW fibonacci number into the sum
sum_of_fibonacci_number = F_n + sum_of_fibonacci_number;
}
//update the n value so they calculate the next fibnacci number
n++;
//and all this while the sum is less than 4 mil
} while (sum_of_fibonacci_number<4000000);
//then your previous sum should be LESS THAN 4 mil
cout << previous_sum << endl;
| |
notice that we check
sum_of_fibonacci_number and result is
previous_sum. to "answer" the question, we must have the condition as 4 mil.
Do this for all fibonacci numbers less than 4,000,000. |
we cannot just assume that we know the final value before 4 mil. this will make your code pretty much "just for this case, i can solve it", and not flexible if say, make the limit 400? 8 mil?
its a little bit complex, i have to admit. so please do ask if you still do not understand. hope this helps :)