Home > Java > javaTutorial > body text

Java algorithm recursive algorithm to calculate factorial

高洛峰
Release: 2017-01-17 13:29:14
Original
1267 people have browsed it

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));
  
  }
  
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!