-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathFibonacciInt.java
More file actions
74 lines (67 loc) · 2.05 KB
/
FibonacciInt.java
File metadata and controls
74 lines (67 loc) · 2.05 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 FibonacciInt to list all the Fibonacci numbers,
* which can be expressed as an int (i.e., 32-bit signed integer
* in the range of [-2147483648, 2147483647]). The output shall look like:
*
* F(0) = 1
* F(1) = 1
* F(2) = 2
* ...
* F(45) = 1836311903
* F(46) is out of the range of int
*
* Hints:
* The maximum and minimum values of a 32-bit int are kept in constants Integer.MAX_VALUE
* and Integer.MIN_VALUE, respectively.
*
* Try these statements:
*
* System.out.println(Integer.MAX_VALUE);
* System.out.println(Integer.MIN_VALUE);
* System.out.println(Integer.MAX_VALUE + 1);
*
* Take note that in the third statement, Java Runtime does not flag out an overflow error,
* but silently wraps the number around. Hence, you cannot use F(n-1) + F(n-2) > Integer.MAX_VALUE
* to check for overflow. Instead, overflow occurs for F(n) if (Integer.MAX_VALUE – F(n-1)) < F(n-2)
* (i.e., no room for the next Fibonacci number).
*
* Write a similar program for Tribonacci numbers.
*/
package javaexercises.difficult;
/**
*
* @author User
*/
public class FibonacciInt {
public static void main(String[] args)
{
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.MAX_VALUE + 1);
FibonacciInt aFibonacciInt = new FibonacciInt();
aFibonacciInt.printFibonacci();
}
private void printFibonacci()
{
int fb1 = 1;
int fb2 = 1;
int fbn = 0;
int i = 1;
System.out.printf("F(%1$d) = %2$d\n", 0, fb2);
System.out.printf("F(%1$d) = %2$d\n", 1, fb1);
while (true)
{
i++;
fbn = fb1 + fb2;
if (Integer.MAX_VALUE - fb1 > fb2) {
System.out.printf("F(%1$d) = %2$d\n", i, fbn);
}
else {
System.out.printf("F(%1$d) is out of the range of int\n", i);
break;
}
fb2 = fb1;
fb1 = fbn;
}
}
}