Recursive factorial, java recursive factorial

Source: Internet
Author: User

Recursive factorial, java recursive factorial

| -- Code

Package com. collection; public class Demo2 {public static void main (String [] args) {/*** calculate the factorial of 5 * // solution 1: normal loop int I = 1; for (int x = 1; x <= 5; x ++) {I = I * x;} // System. out. println (I); // solution 2: recursive System. out. println (jc (5);} public static int jc (int I) {if (I = 1) return 1; elsereturn I * jc (I-1 );}}

Process Analysis Diagram




Factorial n! Recursive Algorithm

# Include <stdio. h>
Double fun (int n );
Int main (void)
{
Int n;
Printf ("Enter n :");
Scanf ("% d", & n );
Printf ("% lf \ n", fun (n ));
Return 0;
}
Double fun (int n)
{
If (n = 0 | n = 1)
Return 1;
Else
Return n * fun (n-1 );
}

How can we use recursive functions to calculate factorial?

Int jiecheng (int n)
{
If (n = 1) // if n is equal to 1, return directly.
Return 1;
Else // otherwise, n * jiecheng (n-1) is returned)
Return n * jiecheng (n-1 );
}
For example, n = 3. the running process is as follows:
Call back
Main function 6
Zookeeper
Jiecheng (3) 3 * jiecheng (2) = 3*2 * jiecheng (1) = 3*2*1
Zookeeper
Jiecheng (2) 2 * jiecheng (1) = 2*1
Zookeeper
Jiecheng (1) → 1

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.