简体   繁体   中英

Loop for, condition 2, doesn't comply

I'm a student with limited JavaScript knowledge (first year) and need help with Project Euler #2.

 var arr = [1, 2]; var total = 2; var x = 0; var y = 1; for (var i; total < 4000000; x++, y++) { i = arr[x] + arr[y]; arr.push(i); if (i % 2 == 0) { total += i } } console.log(total); 

My loop is supposed to stop when the total is less than 4,000,000 but for some reason, the total is 4,613,732.

Your code is 'not' doing anything unusual, the for is running until total is more than 4,000,000.

For example if i were to add 20 each time my for loops to my total and i check every time if my total is more than 50, it will run until i get 60. not less than 60 and it will never be 50 because im adding 20 each for.

since the loop is adding 20 for each loop, in your case is the same, just add an if inside your loop, checking if the total is bigger than what you actually want, if it is, break it and do not add the value that will make it go over your desired value.

So:

My loop is supposed to stop after total is equal to 4,000,000 but for some reason, the total is 4,613,732.

what you are adding maybe just is never going to make total exactly 4,000,000 and if it is then just change your condition to total <= 4000000; instead of total < 4000000;

Here is the problem statement from Project Euler #2 :

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.

You have misinterpreted "four million" to be the upper bound on the sum , whereas it is actually the upper bound on the individual numbers.

Therefore the loop condition should be i <= 4000000 ; but that's not all - you need to rearrange the conditions because i is set inside the loop, so the condition will not catch the last number added.

for (var i;; x++, y++) {
  i = arr[x] + arr[y];
  if (i > 4000000) break; // move condition to here
  arr.push(i);
  if (i % 2 == 0) {
    total += i
  }
}

I find it easier to think my way through recursive functions when they're expressed using functional style

 const projectEuler2 = (limit = 0, sum = 0, a = 0, b = 1) => a > limit ? sum : projectEuler2 ( limit , a & 1 ? sum : sum + a , b , a + b ) console.log (projectEuler2 (4e6)) // 4613732 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM