Home > JAVA > Is Fibo

Is Fibo

Problem:

You are given an integer, N. Write a program to determine if N is an element of the Fibonacci Sequence.

Solution I choose is using this formula:

fibocheck or fibocheck2

 

Then check if the result is a perfect square.

Java code:


public class IsFibo {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = in.nextInt();
long[] arrays = new long[a];
for(int i=0; i < a; i++) {
arrays[i] = in.nextLong();
}
for(int i=0; i < arrays.length; i++) {
System.out.println(isFibo(arrays[i]));
}
}

private static String isFibo(long suspectFibo) {
if((Math.sqrt(5 * Math.pow(suspectFibo, 2) + 4)%1 == 0)
|| (Math.sqrt(5 * Math.pow(suspectFibo, 2) - 4)%1 == 0)) {
return "IsFibo";
}
return "IsNotFibo";
}
}

Result for 3 input (5, 7, 8):

isFibo

Source:

  1. https://www.hackerrank.com/challenges/is-fibo
  2. http://en.wikipedia.org/wiki/Fibonacci_number#Recognizing_Fibonacci_numbers
  3. http://en.wikipedia.org/wiki/Square_number
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: