You are given an integer, N. Write a program to determine if N is an element of the Fibonacci sequence.
The first few elements of the Fibonacci sequence are 0,1,1,2,3,5,8,13,⋯. A Fibonacci sequence is one where every element is a sum of the previous two elements in the sequence. The first two elements are 0 and 1.
Formally:
fib0fib1⋮fibn=0=1=fibn−1+fibn−2∀n>1
Input Format
The first line contains T, number of test cases.
T lines follow. Each line contains an integer N.
Output Format
Display IsFibo
if N is a Fibonacci number and IsNotFibo
if it is not. The output for each test case should be displayed in a new line.
Constraints
1≤T≤105
1≤N≤1010
Sample Input
3
5
7
8
Sample Output
IsFibo
IsNotFibo
IsFibo
Explanation
5 is a Fibonacci number given by fib5=3+2
7 is not a Fibonacci number
8 is a Fibonacci number given by fib6=5+3
SOLUTION:
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
public class FibonacciTester {
private static BigDecimal zero = BigDecimal.valueOf(0);
private static BigDecimal one = BigDecimal.valueOf(1);
private static BigDecimal two = BigDecimal.valueOf(2);
private static BigDecimal four = BigDecimal.valueOf(4);
private static BigDecimal five = BigDecimal.valueOf(5);
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t!=0){
BigDecimal num =sc.nextBigDecimal();
if (isFibonacci(num)) {
System.out.println("IsFibo");
} else {
System.out.println("IsNotFibo");
}
t=t-1;
}
}
public static boolean isFibonacci(BigDecimal num) {
if (num.compareTo(zero) <= 0) {
return false;
}
BigDecimal base = num.multiply(num).multiply(five);
BigDecimal possibility1 = base.add(four);
BigDecimal possibility2 = base.subtract(four);
return (isPerfectSquare(possibility1) || isPerfectSquare(possibility2));
}
public static boolean isPerfectSquare(BigDecimal num) {
BigDecimal low = zero;
BigDecimal high = num;
while (low.compareTo(high) <= 0) {
BigDecimal mid = low.add(high).divide(two).setScale(0, RoundingMode.DOWN);
BigDecimal square = mid.multiply(mid);
int comparison = square.compareTo(num);
if (comparison == 0) {
return true;
} else if (comparison > 0) {
high = mid.subtract(one);
} else {
low = mid.add(one);
}
}
return false;
}
}