Factorial using Recursion in Java

前端 未结 18 1337
春和景丽
春和景丽 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 14:02

    In my opinion, and that being the opinion of someone with beginner level knowledge of java, I would suggest that the n == 1 to be changed to n <= 1 or (n == 0)||(n==1) because the factorial of 0 is 1.

    0 讨论(0)
  • 2020-11-27 14:03
    public class Factorial2 {
        public static long factorial(long x) {
            if (x < 0) 
                throw new IllegalArgumentException("x must be >= 0");
            if (x <= 1) 
                return 1;  // Stop recursing here
            else 
               return x * factorial(x-1);  // Recurse by calling ourselves
        }
    }
    
    0 讨论(0)
  • 2020-11-27 14:04

    The key point that you missing here is that the variable "result" is a stack variable, and as such it does not get "replaced". To elaborate, every time fact is called, a NEW variable called "result" is created internally in the interpreter and linked to that invocation of the methods. This is in contrast of object fields which linked to the instance of the object and not a specific method call

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

    Although this is old, it still keeps coming up pretty well in google. So I figured I'd mention this. No one mentioned to check for when x = 0.

    0! and 1! both = 1.

    This isn't being checked with the previous answers, and would cause a stack overflow, if fact(0) was run. Anyway simple fix:

    public static int fact(int x){
        if (x==1 | x==0)
            return 1;
        return fact(x-1) * x;
    }// fact
    
    0 讨论(0)
  • 2020-11-27 14:05

    Using Java 8 and above, using recursion itself

      UnaryOperator<Long> fact = num -> num<1 ? 1 : num * this.fact.apply(num-1);
    

    And use it like

      fact.apply(5); // prints 120
    

    Internally it calculate like

    5*(4*(3*(2*(1*(1)))))
    
    0 讨论(0)
  • 2020-11-27 14:07
    public class Factorial {
    
        public static void main(String[] args) {
            System.out.println(factorial(4));
        }
    
        private static long factorial(int i) {
    
            if(i<0)  throw new IllegalArgumentException("x must be >= 0"); 
            return i==0||i==1? 1:i*factorial(i-1);
        }
    }
    
    0 讨论(0)
提交回复
热议问题