使用递归完成 1 到 100 的累加
Sunny-117 opened this issue · comments
使用递归完成 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)
}
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));