Fibonacci Number Algorithm
The Fibonacci Number Algorithm is a mathematical algorithm used to determine the Fibonacci sequence, which is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. The Fibonacci sequence has been widely studied and applied in various fields, including computer science, mathematics, and even in nature. The algorithm is based on the simple recurrence relation: F(n) = F(n-1) + F(n-2), where F(n) denotes the nth Fibonacci number.
There are multiple ways to implement the Fibonacci Number Algorithm, including iterative, recursive, and matrix exponentiation methods. The iterative method involves initializing two variables to represent the two previous Fibonacci numbers and then repeatedly updating them to generate the next number in the sequence. This method is efficient in terms of time complexity as it has a linear runtime. On the other hand, the recursive method calculates the nth Fibonacci number by recursively calling the function with smaller values of n until the base case (n=0 or n=1) is reached. However, this approach has an exponential runtime, making it inefficient for large values of n. The matrix exponentiation method uses linear algebra to calculate the nth Fibonacci number in logarithmic time, thus providing a more efficient solution for larger values of n. Overall, the Fibonacci Number Algorithm has various applications and implementations, and its study has contributed significantly to the understanding of mathematical patterns and sequences.
package Maths;
/**
* Fibonacci: 0 1 1 2 3 5 8 13 21 ...
*/
public class FibonacciNumber {
public static void main(String[] args) {
assert isFibonacciNumber(1);
assert isFibonacciNumber(2);
assert isFibonacciNumber(21);
assert !isFibonacciNumber(9);
assert !isFibonacciNumber(10);
}
/**
* Check if a number is perfect square number
*
* @param number the number to be checked
* @return <tt>true</tt> if {@code number} is perfect square, otherwise <tt>false</tt>
*/
public static boolean isPerfectSquare(int number) {
int sqrt = (int) Math.sqrt(number);
return sqrt * sqrt == number;
}
/**
* Check if a number is fibonacci number
* This is true if and only if at least one of 5x^2+4 or 5x^2-4 is a perfect square
*
* @param number the number
* @return <tt>true</tt> if {@code number} is fibonacci number, otherwise <tt>false</tt>
* @link https://en.wikipedia.org/wiki/Fibonacci_number#Identification
*/
public static boolean isFibonacciNumber(int number) {
return isPerfectSquare(5 * number * number + 4) || isPerfectSquare(5 * number * number - 4);
}
}