<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title> Five calculation methods of factorial </title>
<script type="text/javascript">
/*use strict*/
/* Method 1 Optimization of tail recursion */
// Constructing a function with tail recursion . Because it returns the result of its own call , So it's tail recursion
//JavaScript There is currently no optimization for this form of recursion
var factorial = function factorial(i,a){
console.log(i,a);
a = a || 1;
console.log(i,a);
if(i<2){
return a;
}
// return factorial(i-1,a*i);
return factorial(i-1,a*i);
};
console.log(" This is the top 4 factorial ：",factorial(4));

/* Method 2 */
// use arguments.callee It can be used regardless of whether the function name changes or remains unchanged
function fac(num){
if(num<=1){
return 1;
}else{
// closure
return num*fac(--num); // Method 1
//return num*fac(num-1); // Method 2
// return num*arguments.callee(num-1);// Method 3
// return num*arguments.callee(--num);// Method 4
/* But it cannot be accessed through script in strict mode arguments.callee*/
}
}
var result = fac(4);

console.log(" This is the bottom 4 factorial ：",result);

// Method 3
var factorial = function fac(num){
if(num<=1){
return 1;
}else{
// closure
return num*fac(num-1);

}
}
var result = factorial(4);
console.log(" This is the last one 4 factorial ：",result);

// Method 4
function fac(n){
return n>1? n*fac(n-1):1;
}
console.log(" Method 4 Results ",fac(4));
// ECAMscript There is no block level scope and variables defined within the loop can also be accessed externally
// JS
It does have a function scope 【 But there is no block level scope 】. That means that the parameters and variables defined in the function are invisible outside the function . Variables defined anywhere within a function , Visible anywhere inside the function .

// Method 5 for loop ( Using loop statements )
function test1(num){
for(var i=num-1;i>=1;i--){
num *=i;
}
return num;
}
console.log("for Circular recursion ",test1(5));

// Method 6 white loop
function test2(num){
var result = num;
while(num>1){
num--;
result *=num;
}
return result;
}

console.log("while Circular recursion ",test2(4));

//5 Sum of factorials of

function test3(num){

var n=num;

var total = 0;

for(var i=1;i<=n;i++){

var temp = 1;

for(var j=i;j>=1;j--){

temp *=j;

}

total += temp;

}

}
console.log("5 The sum of the factorials of is ",test3(5))

/* label identification
use label You can add tags to your code , For future use
label : for(int i=0;i<10;i++){
if(i == 5){
break label;
}
}
Loop key
break Jump out of the loop
continue End this cycle , Next cycle */
</script>