Java Reference
In-Depth Information
public class Factorial2 {
public static void main(String[] args) {
long limit = 20L; // to calculate factorial of integers up to
this value
long factorial = 1L; // factorial will be calculated in this
variable
// Loop from 1 to the value of limit
OuterLoop:
for(long i = 1L; i <= limit; ++i) {
factorial = 1;
// Initialize factorial
for(long j = 2L; j <= i; ++j) {
if(i > 10L && i % 2L == 1L) {
continue OuterLoop;
// Transfer to the outer loop
}
factorial *= j;
}
System.out.println(i + "! is " + factorial);
}
}
}
Factorial2.java
If you run this it produces the following output:
1! is 1
2! is 2
3! is 6
4! is 24
5! is 120
6! is 720
7! is 5040
8! is 40320
9! is 362880
10! is 3628800
12! is 479001600
14! is 87178291200
16! is 20922789888000
18! is 6402373705728000
20! is 2432902008176640000
How It Works
The outer loop has the label OuterLoop . In the inner loop, when the condition in the if statement is true ,
the labeled continue is executed causing an immediate transfer to the beginning of the next iteration of
the outer loop. The condition in the if statements causes the calculation of the factorial to be skipped for
odd values greater than 10.
Search WWH ::




Custom Search