Factorial Recursive Algorithm

Source: Internet
Author: User
Code
// Factorial RecursionAlgorithm(A combination of N numbers)
Function Calfactorial (N)
{
If (N <   0 )
{
Return   ' N cannot be negative. ' ;
}
Else   If (N =   0 )
{
Return   1 ;
}
Else
{
Return N * Calfactorial (n -   1 );
}
}

Function Factorialwork (anumber, recursnumber ){
// Recursnumber keeps track of the number of iterations so far.
If (Anumber =   0 ){ // If the number is 0, its factorial is 1.
Return   1 .;
} Else {
If (Recursnumber >   100 ){
Return ( " Too many levels of recursion. " );
} Else { // Otherwise, recurse again.
Return (Anumber * Factorialwork (anumber -   1 , Recursnumber +   1 ));
}
}
}

Function Factorial (anumber ){
// Use Type annotation to only accept numbers coercible to integers.
// Double is used for the return type to allow very large numbers to be returned.
If (Anumber <   0 ){
Return ( " Cannot take the factorial of a negative number. " );
} Else { // Call the recursive function.
Return Factorialwork (anumber, 0 );
}
}

//Call the factorial function for two values.
Alert (factorial (5));
Alert (factorial (80));

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.