<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<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 above.4 factorial:",factorial(4));

/* Method two*/
// usearguments.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 two
// return num*arguments.callee(num-1);// Method three
// return num*arguments.callee(--num);// Method four
/* But it cannot be accessed through script in strict modearguments.callee*/
}
}
var result = fac(4);

console.log(" This is below.4 factorial:",result);

// Method three
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 one4 factorial:",result);


// Method four
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 five for loop ( Using loop statements)
function test1(num){
for(var i=num-1;i>=1;i--){
num *=i;
}
return num;
}
console.log("for Cyclic recursion",test1(5));

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

console.log("while Cyclic 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;


}

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




/* label Identification
Uselabel 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>
</head>
<body>

</body>
</html>