I am trying to find whether a given number is fibonocci or not.The logic i am using id 5*n^2+4 or 5*n^2-4 will be a perfect square
.The code is as follows
import java.util.*;
import java.math.*;
public class Solution {
public static void main(String [] args){
Scanner input=new Scanner(System.in);
int number=input.nextInt();
int holder[]=new int[number];
for(int i=0;i<number;i++){
holder[i]=input.nextInt();
checkFib(holder[i]);
}
}
private static void checkFib(int i) {
// TODO Auto-generated method stub
long fivePlus=(long) (5*Math.pow(i, 2)+4);
long fiveMinus=(long)(5*Math.pow(i, 2)-4);
boolean check=checkSquare(fivePlus,fiveMinus);
if(check==true){
System.out.println("IsFibo");
}else{
System.out.println("IsNotFibo");
}
}
private static boolean checkSquare(long fivePlus, long fiveMinus) {
// TODO Auto-generated method stub
boolean ret1,ret2;
if(Math.sqrt(fivePlus)==Math.floor((Math.sqrt(fivePlus)))){
ret1=true;
}else{
ret1=false;
}
if(Math.sqrt(fiveMinus)==Math.floor((Math.sqrt(fiveMinus)))){
ret2=true;
}else{
ret2=false;
}
return (ret1||ret2);
}
}
The input format will be 2 // for two test case 5 //5 and 6 representing test data 6 ps:Even though the answers regarding using BigInteger is appreciable ,but i am not looking at big integer as my test data is in the range of long .