-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathFactorialInt.java
More file actions
74 lines (65 loc) · 2.06 KB
/
FactorialInt.java
File metadata and controls
74 lines (65 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* Write a program called Factorial1to10, to compute the factorial of n,
* for 1 ≤ n ≤ 10. Your output shall look like:
*
* The factorial of 1 is 1
* The factorial of 2 is 2
* ...
* The factorial of 10 is 3628800
*
* Modify your program (called FactorialInt), to list all the factorials,
* that can be expressed as an int (i.e., 32-bit signed integer). Your output
* shall look like:
*
* The factorial of 1 is 1
* The factorial of 2 is 2
* ...
* The factorial of 12 is 479001600
* The factorial of 13 is out of range
*
* Hints: Overflow occurs for Factorial(n+1) if (Integer.MAX_VALUE / Factorial(n)) < (n+1).
* Modify your program again (called FactorialLong) to list all the factorial
* that can be expressed as a long (64-bit signed integer). The maximum value
* for long is kept in a constant called Long.MAX_VALUE.
*/
package javaexercises.difficult;
public class FactorialInt {
public static void main(String[] args)
{
FactorialInt aFactorialInt = new FactorialInt();
System.out.println("Int factorials:");
aFactorialInt.printIntFactorials();
System.out.println("Long factorials:");
aFactorialInt.printLongFactorials();
}
private void printIntFactorials()
{
int i = 1;
int fn = 1;
while (true)
{
System.out.printf("The factorial of %1$d is is %2$d.\n", i, fn);
if (Integer.MAX_VALUE / fn < (i+1)) {
System.out.printf("The factorial of %d is out of range.\n", (i+1));
break;
}
i++;
fn *= i;
}
}
private void printLongFactorials()
{
long i = 1L;
long fn = 1L;
while (true)
{
System.out.printf("The factorial of %1$d is is %2$d.\n", i, fn);
if (Long.MAX_VALUE / fn < (i+1)) {
System.out.printf("The factorial of %d is out of range.\n", (i+1));
break;
}
i++;
fn *= i;
}
}
}