# 程序的迭代

### 线性的递归和迭代

``n! = n * (n - 1) * (n - 2) ... * 3 * 2 * 1; ``

1. 1的阶乘是1
2. 对于任意一个大于1的整数n， n的阶乘是n与n-1的阶乘的乘积

``let factorial = (n) =>    n > 1 ? n * factorial(n - 1) : 1; console.log(factorial(5)); //120 ``

``function factorial(n, acc = 1){   if (n <= 1) return acc;   return factorial(n - 1, n * acc); } console.log(factorial(5)); //120 ``

``factorial(5) 5 * factorial(4) 5 * (4 * factorial(3)) 5 * (4 * (3 * factorial(2))) 5 * (4 * (3 * (2 * factorial(1)))) 5 * (4 * (3 * (2 * (1)))) 5 * (4 * (3 * (2))) 5 * (4 * (6)) 5 * (24) 120 ``

``factorial(5, 1) factorial(4, 5); factorial(3, 20); factorial(2, 60); factorial(1, 120); 120 ``

``"use strict";  var factorial = function factorial(n) {   return n > 1 ? n * factorial(n - 1) : 1; }; console.log(factorial(5)); //120 ``

``"use strict";  function factorial(_x2) {   var _arguments = arguments;   var _again = true;    _function: while (_again) {     var n = _x2;     _again = false;     var acc = _arguments.length <= 1 || _arguments[1] === undefined ? 1 : _arguments[1];      if (n <= 1) return acc;     _arguments = [_x2 = n - 1, n * acc];     _again = true;     acc = undefined;     continue _function;   } }; console.log(factorial(5)); //120 ``

``let factorial = (n) => {    let ret = 1;   for(let i = 2; i <= n; i++){     ret *= i;   }    return ret; } console.log(factorial(5)); //120 ``

``0, 1, 1, 2, 3, 5, 8, 13, 21, ... ``

``let fib = (n) => {   if(n === 0) return 0;   if(n === 1) return 1;   return fib(n - 1) + fib(n - 2); };  console.log(fib(7)); //13 ``

``[a, b] = [a + b, a]; ``

``let fib = (n, a = 1, b = 0) => {   if(n === 0) return b;   return fib(n - 1, a + b, a); };  console.log(fib(7)); //13 ``

``"use strict";  var fib = function fib(_x5) {   var _arguments2 = arguments;   var _again2 = true;    _function2: while (_again2) {     var n = _x5;     var a = _arguments2.length <= 1 || _arguments2[1] === undefined ? 1 : _arguments2[1];     _again2 = false;     var b = _arguments2.length <= 2 || _arguments2[2] === undefined ? 0 : _arguments2[2];      if (n === 0) return b;     _arguments2 = [_x5 = n - 1, a + b, a];     _again2 = true;     a = b = undefined;     continue _function2;   } };  console.log(fib(7)); //13 ``

``let fib = (n) => {   if(n === 0) return 0;   let a = 1, b = 0;   for(let i = 2; i <= n; i++){     [a, b] = [a + b, a];   }   return a; };  console.log(fib(7)); //13 ``

``let deepCopy = (obj) => {   if(obj == null) return obj;   let copyed = {};    for(let key in obj){     if(typeof obj[key] === "object"){       copyed[key] = deepCopy(obj[key]);     }else{       copyed[key] = obj[key];     }   }    return copyed; };  let a = {a:{x:1, y:2}, b:3, c:function(){}}; let b = deepCopy(a); console.log(b.a.x); //1  b.a.y = 3; console.log(b.a.y, a.a.y); //3, 2 ``

``function qsort(arr){   if(arr.length <= 1) return arr;   var c = arr[0], rest = arr.slice(1);   return qsort(rest.filter(item => item < c))     .concat([c]).concat(qsort(rest.filter(item => item >= c))); } ``