Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用递归完成 1 到 100 的累加 #138

Open
Sunny-117 opened this issue Nov 3, 2022 · 7 comments
Open

使用递归完成 1 到 100 的累加 #138

Sunny-117 opened this issue Nov 3, 2022 · 7 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@lxy-Jason
Copy link
Contributor

function sum(num){
    if(num === 1) return 1
    return num + sum(num - 1);
}
console.log(sum(100));

@weirong111
Copy link

尾递归优化,一行代码解决

function process(cur, total = 0) {
  return cur === 0 ? total : process(cur - 1, total + cur);
}

@CwRv07
Copy link
Contributor

CwRv07 commented Mar 7, 2023

function accumulate(curr, max, total = 0) {
  return curr > max ? total : accumulate(curr + 1, max, total + curr);
}

console.log(accumulate(1,100)); // 5050

@MoYuanJun
Copy link

// 直接就是一个循环
const sum = (min, max) => {
  let total = 0

  while(min <= max) {
    total += min
    min+=1
  }
  return total
}

// 递归:  相当于 min + (min + 1) + (min + 1 + 1)……
const sum1 = (min, max) => {
  if (min === max) return min
  return min + sum1(min + 1, max)
}

@fangbw17
Copy link

fangbw17 commented Mar 16, 2023

function recursionNum(max = 0, total = 0) {
    return max === 0 ? total : recursionNum(max - 1, total + max)
}

@bearki99
Copy link

function process(cur, sum = 0) {
  return cur === 0 ? sum : process(cur - 1, sum + cur);
}
console.log(process(100));

@gocpekfdj
Copy link

function f(n){
if(n>100)
return 0;
return n+f(n+1);
}
console.log(f(1));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

8 participants