Java 常见例子

正整数的阶乘是所有小于或等于该数字的正整数的乘积。

数字的阶乘n = n! = n(n-1)(n-2)...1

例如:

5! = 5 × 4 × 3 × 2 × 1 = 120

4! = 4 × 3 × 2 × 1 = 24

方法 1:使用递归方法

在下面的示例中,递归方法称为 factorial() 用于计算数字的阶乘。

public class MyClass {
  static int factorial(int x) {
    if (x == 0 || x == 1)
      return 1;
    else 
      return x*factorial(x-1);    
  }

  public static void main(String[] args) {
    System.out.println("10! =  " + factorial(10));
    System.out.println("6! =  " + factorial(6));
  }
} 

上面的代码将给出以下输出:

10! =  3628800
6! =  720 

方法 2:使用迭代方法

数字的阶乘也可以使用迭代方法计算。

public class MyClass {
  static int factorial(int x) {
    int finalnum = 1;
    for(int i = x; i > 0; i--) {
      finalnum = finalnum * i;
    }
    return finalnum;  
  }

  public static void main(String[] args) {
    System.out.println("10! =  " + factorial(10));
    System.out.println("6! =  " + factorial(6));
  }
} 

上面的代码将给出以下输出:

10! =  3628800
6! =  720 

方法3:使用三元运算符

在下面的示例中,使用三元运算符计算数字的阶乘。

public class MyClass {
  static int factorial(int x) {
    int y = (x == 0 || x == 1)? 1 : x*factorial(x-1);
    return y;  
  }

  public static void main(String[] args) {
    System.out.println("10! =  " + factorial(10));
    System.out.println("6! =  " + factorial(6));
  }
} 

上面的代码将给出以下输出:

10! =  3628800
6! =  720