Loading...
Loading...
Loading...
A library has n different books to put in a row on a shelf. The number of different orders is n! = 1 × 2 × … × n, and 0! is 1 (there is one way to arrange nothing).
Write a method static long factorial(int n) that returns n! using a loop, and print the result for the given n.
Example 1
Input
5
Output
120
1 × 2 × 3 × 4 × 5 = 120.
Example 2
Input
0
Output
1
By definition 0! = 1.
Try the problem first. Open one hint at a time.
Start a long result = 1; and multiply it by every number from 2 to n.
With result starting at 1, n = 0 and n = 1 need no special case.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor