Recursive function in JS

recursive function

  • What is recursion?
    • In the programming world, recursion is a means of calling yourself
    • Recursive function: Inside a function, it calls itself and repeats
// 下面这个代码就是一个最简单的递归函数
// 在函数内部调用了自己,函数一执行,就调用自己一次,在调用再执行,循环往复,没有止尽
function fn() {
  fn()
}
fn()
  • In fact, recursive functions are very similar to loops

  • It needs initialization, self-increment, code execution, and conditional judgment, otherwise it is an endless recursive function, which we call dead recursion

Second, use recursion to solve some problems

2.1 Using recursion to find the factorial of 100

  • Idea: Finding the factorial of 100 is the factorial of 99 times 100, which is equivalent to the product of n*(n-1) for the factorial of n
function a(n) {
    if (n == 1) {
        return 1
    }
    return a(n - 1) * n
}
console.log(a(100));

2.2 Write a recursive function dep() to meet the requirements: the annual salary is 10k, and the annual increase is 0.5%, so how much will the salary be after 50 years?

  • Idea: It will increase every year, starting from 10,000, and the annual work will be 1.005 times that of last year
function dep(y) {
    if (y == 1) {
        return 10000
    }
    return dep(y - 1) * 1.005
}
var a = dep(50)
console.log(a);

2.3 Using recursion to find the Fibonacci sequence

  • Fibonacci sequence :1 1 2 3 5 8 13 21 34 ...
  • Write a function, pass in 5, and output what is the fifth digit of the Fibonacci sequence?
  • Idea: First of all, we can see that the first item and the second item are both one. When we recurse, when n is equal to 1 or 2, we return 1 to end the recursion. Then we can see that the addition of the first two numbers equals the third number, so the nth number is equal to the addition of the n-1th and n-2th numbers, and then use recursion.
function fun(n) {
    if (n == 1 || n == 2) {
        return 1
    }
    return fun(n - 1) + fun(n - 2)
}
var res = fun(5)
console.log(res);

Guess you like

Origin blog.csdn.net/liu0218/article/details/126549252