You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JavaScript递归函数计算1-100偶数和的输出异常问题

Fixing Your Recursive JavaScript Function for Summing Evens 1-100

Hey there! Let's sort out that recursive function you're working on. It sounds like right now, your code is returning 0 for odd numbers and the number itself for evens—but it's not actually accumulating the total sum. That's a super common pitfall with recursion when you forget to tie the current value to the rest of the recursive calls.

First, Let's Diagnose the Likely Issue

Chances are your current code looks something like this (I've guessed based on your description):

function sumEvens(n) {
  if (n === 0) return 0;
  if (n % 2 !== 0) return 0;
  else return n;
}

The problem here is that this function only evaluates the current number—it doesn't recursively add the sum of all smaller even numbers. It just returns the current even (or 0 for odds) and stops, so you never build up the total.

The Correct Recursive Approach

Recursion works by breaking the problem into smaller subproblems. For summing evens from 1 to 100, we need to:

  1. Check if the current number is even—if yes, add it to the sum of evens below it.
  2. If it's odd, skip it and move to the next number.
  3. Set a base case to stop the recursion when we go below 1.

Here's the working code:

function sumEvenNumbers(n) {
  // Base case: when n drops below 1, there are no more numbers to sum
  if (n < 1) return 0;
  
  // If current number is even, add it to the sum of evens from 1 to n-1
  if (n % 2 === 0) {
    return n + sumEvenNumbers(n - 1);
  } else {
    // If it's odd, just recurse with n-1 (no addition needed)
    return sumEvenNumbers(n - 1);
  }
}

// Test it out!
console.log(sumEvenNumbers(100)); // Output: 2550

Optimized Version (Fewer Recursive Calls)

Since we only care about even numbers, we can skip all the odd numbers in one step by subtracting 2 instead of 1. This cuts the number of recursive calls in half:

function sumEvensOptimized(n) {
  // Base case: if n is less than 2, there are no evens left to sum
  if (n < 2) return 0;
  
  // If n is even, add it to the sum of evens two numbers below
  if (n % 2 === 0) {
    return n + sumEvensOptimized(n - 2);
  } else {
    // If n is odd, use the previous even number (n-1)
    return sumEvensOptimized(n - 1);
  }
}

console.log(sumEvensOptimized(100)); // Still outputs 2550

Quick Recap

The core issue with your original code was that it didn't combine the current value with the result of the recursive call. Recursion relies on building up the solution by adding (or combining) the current step's output with the subproblem's output—you can't just return the current value alone!

内容的提问来源于stack exchange,提问作者Reza Poorbaferani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:41:16