首页 > 代码库 > 递归算法

递归算法

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>递归算法</title>
 6     <script>
 7 
 8         //递归算法:1+2+3...+n
 9         function fn(a) {
10             return a > 1 ? fn(a - 1) + a : 1;
11         }
12 
13         //递归算法:1!、2!、3!...、n!
14         function fn1(b) {
15             return b > 1 ? fn1(b - 1) * b : 1;
16         }
17 
18         //递归算法:1!+2!+3!...+n!
19         function fn2(c) {
20             return c > 1 ? fn2(c - 1) + fn1(c) : 1;
21         }
22 
23         document.write(fn2(5));
24     </script>
25 
26 
27 //公式推导:
28     <pre>
29         递归算法:1+2+3...+n
30         f1 = 1 ;
31         f2 = f1 + 2;
32         fn = f(n-1)+n;
33         function fn(n){
34         while(n>1){
35         return fn(n-1)+n;
36         }
37         }
38 
39         递归算法:1!、2!、3!...、n!
40         f1=1;
41         f2=f1*2;
42         f3=f2*3;
43         fn=f(n-1)*n;
44 
45         递归算法:1!+2!+3!...+n!
46         f1=1;
47         f2=f1+1*2;
48         f3=f2+1*2*3;
49         f4=f3+1*2*3*4;
50         fn=f(n-1)+n!
51     </pre>
52 </head>
53 <body>
54 
55 </body>
56 </html>

 

递归算法