集册 Java实例教程 经典阶乘与非阶乘

经典阶乘与非阶乘

欢马劈雪     最近更新时间:2020-01-02 10:19:05

505
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
具有非递归解的经典阶乘
/* 来自 nowjava.com - 时  代  Java*/

public class Main {

  public static void main(String[] args) {

    int n = 5;

    long fact;

    fact = factorial(n);

    System.out.println("The factorial of " + n + " is " + fact + ".");

  }


  private static long factorial(int n) {

    long f = 1;

    for (int i = 1; i <= n; i++)

      f = f * i;

    return f;

  }


}