Definition
A sequence of numbers that follows a specific pattern. The first two numbers are always 0 and 1, and the third number is the sum of the first and second numbers.
Example of Fibonacci sequence
1,1,2,3,5,8,13,21,34,55...
Examples
Index | Fibonacci Number | Calculation |
---|---|---|
0 | 0 | 0 |
1 | 1 | 1 |
2 | 1 | 0+1 |
3 | 2 | 1+1 |
4 | 3 | 1+2 |
5 | 5 | 2+3 |
6 | 8 | 3+5 |
7 | 13 | 5+8 |
8 | 21 | 8+13 |
9 | 34 | 13+21 |
10 | 55 | 21+34 |
11 | 89 | 34+55 |
12 | 144 | 55+89 |
13 | 233 | 89+144 |
14 | 377 | 144+233 |
15 | 610 | 233+377 |
16 | 987 | 377+610 |
How to find the Fibonacci number at a specific index
Mathematical (Binet’s simplified formula)
public static int fib(int num) {
double goldenRatio = (1 + Math.sqrt(5)) / 2;
return (int) Math.round(Math.pow(goldenRatio, num) / Math.sqrt(5));
}
Recursive Function
public static int fibRecursive(int num) {
if (num == 0) return 0;
else if (num == 1) return 1;
else return fibRecursive(num - 2) + fibRecursive(num - 1);
}
Loop
public static int fib(int num) {
if (num == 0) return 0;
else if (num == 1) return 1;
else {
int result = 0;
int iterA = 0;
int iterB = 1;
for (int i = 2; i <= num; i++) {
result = iterA + iterB;
iterA = iterB;
iterB = result;
}
return result;
}
}
How to determine if a number is a Fibonacci number
If a number is a Fibonacci number, then either one or both of the expressions below will result in a perfect square:
Perfect Square
When x is a perfect square,
where root{x} must be an integer.
For example, 9 is a perfect squa
댓글 없음:
댓글 쓰기