Factorial using Recursion in Java

前端 未结 18 1313
春和景丽
春和景丽 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: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
        }
    }
    

提交回复
热议问题