Home >Java >javaTutorial >Java algorithm recursive algorithm to calculate factorial

Java algorithm recursive algorithm to calculate factorial

高洛峰
高洛峰Original
2017-01-17 13:29:141283browse

This article will share with you the java algorithm to calculate factorial. When learning Java courses, you often encounter the problem of finding factorial. Today I will discuss it with you.

The code is as follows:

package com.xu.main;
  
import java.util.Scanner;
  
public class P9 {
  
  static long fact(int n)
  {
    if(n <= 1)
    {
      return 1;
    }
    else
    {
      return n * fact(n - 1);
    }
  }
    
  public static void main(String[] args) {
    int i;
    System.out.println("请输入要求阶乘的一个整数:");
    Scanner input = new Scanner(System.in);
    i = input.nextInt();
    System.out.println(i + "的阶乘结果是:"+fact(i));
  
  }
  
}

Run Result:

Java algorithm recursive algorithm to calculate factorial

For more Java algorithm recursive algorithm calculation factorial related articles, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn