Home >Java >javaTutorial >Java Example - Factorial

Java Example - Factorial

黄舟
黄舟Original
2017-02-16 10:15:031748browse

The factorial (English: factorial) of a positive integer is the product of all positive integers less than and equal to the number, and the factorial of 0 is 1. The factorial of a natural number n is written n!.

That is, n!=1×2×3×...×n. Factorial can also be defined recursively: 0!=1, n!=(n-1)!×n.

The following example demonstrates the implementation of Java factorial code:

/*
 author by w3cschool.cc
 MainClass.java
 */public class MainClass {
   public static void main(String args[]) {
      for (int counter = 0; counter <= 10; counter++){
         System.out.printf("%d! = %d\n", counter,
         factorial(counter));
      }
   }
   public static long factorial(long number) {
      if (number <= 1)
         return 1;
      else
         return number * factorial(number - 1);
   }}

The output result of running the above code is:

0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800

The above is the Java example-factorial Content, for more related content, please pay attention to the PHP Chinese website (www.php.cn)!


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