Factorial using Recursion in Java

前端 未结 18 1314
春和景丽
春和景丽 2020-11-27 13:43

I am learning Java using the book Java: The Complete Reference. Currently I am working on the topic Recursion.

Please Note: There are similar questi

相关标签:
18条回答
  • 2020-11-27 13:52

    IMHO, the key for understanding recursion-related actions is:

    1. First, we dive into stack recursively, and with every call we somehow modify a value (e.g. n-1 in func(n-1);) which determines whether the recursion should go deeper and deeper.
    2. Once recursionStopCondition is met (e.g. n == 0), the recursions stops, and methods do actual work and return values to the caller method in upper stacks, thus bubbling to the top of the stack.
    3. It is important to catch the value returned from deeper stack, somehow modify it (multiplying by n in your case), and then return this modified value topwards the stack. The common mistake is that the value from the deepest stack frame is returned straight to the top of the stack, so that all method invocations are ignored.

    Surely, methods can do useful work before they dive into recursion (from the top to the bottom of the stack), or on the way back.

    0 讨论(0)
  • 2020-11-27 13:53

    Here is yet another explanation of how the factorial calculation using recursion works.

    Let's modify source code slightly:

    int factorial(int n) {
          if (n <= 1)
                return 1;
          else
                return n * factorial(n - 1);
    }
    

    Here is calculation of 3! in details:

    Source: RECURSION (Java, C++) | Algorithms and Data Structures

    0 讨论(0)
  • 2020-11-27 13:58
    import java.util.Scanner;
    
    public class Factorial {
        public static void main(String[] args) {
            Scanner keyboard = new Scanner(System.in);
            int n; 
            System.out.println("Enter number: ");
            n = keyboard.nextInt();
            int number = calculatefactorial(n);
            System.out.println("Factorial: " +number);
        }
        public static int calculatefactorial(int n){
            int factorialnumbers=1;
            while(n>0){
             factorialnumbers=(int)(factorialnumbers*n--);   
            }
            return factorialnumbers;
        }
    }
    
    0 讨论(0)
  • 2020-11-27 13:59

    First you should understand how factorial works.

    Lets take 4! as an example.

    4! = 4 * 3 * 2 * 1 = 24
    

    Let us simulate the code using the example above:

    int fact(int n)
        {
            int result;
           if(n==0 || n==1)
             return 1;
    
           result = fact(n-1) * n;
           return result;
        }
    

    In most programming language, we have what we call function stack. It is just like a deck of cards, where each card is placed above the other--and each card may be thought of as a function So, passing on method fact:

    Stack level 1: fact(4) // n = 4 and is not equal to 1. So we call fact(n-1)*n

    Stack level 2: fact(3)

    Stack level 3: fact(2)

    Stack level 4: fact(1) // now, n = 1. so we return 1 from this function.

    returning values...

    Stack level 3: 2 * fact(1) = 2 * 1 = 2

    Stack level 2: 3 * fact(2) = 3 * 2 = 6

    Stack level 1: 4 * fact(3) = 4 * 6 = 24

    so we got 24.

    Take note of these lines:

    result = fact(n-1) * n;
               return result;
    

    or simply:

    return fact(n-1) * n;
    

    This calls the function itself. Using 4 as an example,

    In sequence according to function stacks..

    return fact(3) * 4;
    return fact(2) * 3 * 4
    return fact(1) * 2 * 3 * 4
    

    Substituting results...

    return 1 * 2 * 3 * 4 = return 24
    

    I hope you get the point.

    0 讨论(0)
  • 2020-11-27 14:01

    Well variable "result" is a local variable. When fact() method is called from "main" method variable "result" is stored in different variable.

    Also line : result = fact(n-1) * n; 
    

    here logic is finding factorial using recursion. Recursion in java is a procedure in which a method calls itself.

    Meanwhile you can refer this resource on factorial of a number using recursion.

    0 讨论(0)
  • 2020-11-27 14:02

    To understand it you have to declare the method in the simplest way possible and martynas nailed it on May 6th post:

    int fact(int n) {
        if(n==0) return 1;
        else return n * fact(n-1);
    }
    

    read the above implementation and you will understand.

    0 讨论(0)
提交回复
热议问题