Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

Sunny-117 opened this issue · comments

commented
使用递归完成 1 到 100 的累加
function sum(num){
    if(num === 1) return 1
    return num + sum(num - 1);
}
console.log(sum(100));

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

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

console.log(accumulate(1,100)); // 5050
// 直接就是一个循环
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)
}
function recursionNum(max = 0, total = 0) {
    return max === 0 ? total : recursionNum(max - 1, total + max)
}
commented
function process(cur, sum = 0) {
  return cur === 0 ? sum : process(cur - 1, sum + cur);
}
console.log(process(100));

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