Skip to content

Instantly share code, notes, and snippets.

@vignarajj
Last active January 21, 2019 07:50
Show Gist options
  • Save vignarajj/093fcc8c5ab94e70dff2f31ffd0fd97d to your computer and use it in GitHub Desktop.
Save vignarajj/093fcc8c5ab94e70dff2f31ffd0fd97d to your computer and use it in GitHub Desktop.
To find the next Fibonacci number - Java
import java.util.HashMap;
import java.util.Map;
public class FibonacciExample {
//Check the number is perfect square or not.
static boolean isPerfectSquare(int x) {
int s = (int) Math.sqrt(x);
return (s * s == x);
}
// Returns true if n is a Fibonacci Number, else false
static boolean isFibonacci(int n) {
return isPerfectSquare(5 * n * n + 4)
|| isPerfectSquare(5 * n * n - 4);
}
// find the index of fibonacci number
static int findIndex(int n) {
if (n <= 1) {
return n;
}
int a = 0, b = 1, c = 1;
int res = 1;
while (c < n) {
c = a + b;
res++;
a = b;
b = c;
}
return res;
}
// find the fibonacci number by Index
static int fib(int n) {
if (n <= 1) {
return n;
}
return fib(n - 1) + fib(n - 2);
}
// Find the next fibonacci number
public static int getNextFib(int n) {
int[] fibs = new int[100];
int i = 0;
fibs[0] = 0;
fibs[1] = 1;
for (i = 2; i <= n + 1; i++) {
fibs[i] = fibs[i - 1] + fibs[i - 2];
if (fibs[i] > n) {
return fibs[i];
}
}
if (fibs[i - 1] < n) {
return fibs[i - 1] + n;
}
if(fibs[i-1]== n){
return fibs[i-1]+ fibs[i-2];
}
if (fibs[i] == n - 1 || fibs[i] == n) {
if (n != 0) {
if (n == 1) {
return 2;
} else {
return fibs[i + 1] + fibs[i + 2];
}
} else {
return 1;
}
}
if (fibs[i - 1] == 1) {
return fibs[n + n];
}
return n;
}
//Use hashmap
public static Map<String, String> nextFibonacci(int[] num) {
int len = num.length;
Map<String, String> fibNum = new HashMap<>();
for (int i = 0; i < len; i++) {
if (isFibonacci(num[i])) {
// Using a index of given number and find the next fibonacci number.
// int index = findIndex(num[i])+1;
// int nextFibNum = fib(index);
int nextFibNum = getNextFib(num[i]);
fibNum.put(String.valueOf(i), String.valueOf(nextFibNum));
} else {
fibNum.put(String.valueOf(i), String.valueOf(num[i]) + " is not Fibonacci Number");
}
}
return fibNum;
}
public static void main(String[] args) {
int[] numbers = {1, 21, 8};
for(String nums: nextFibonacci(numbers).values()){
System.out.println(nums);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment