Archive

Posts Tagged ‘fibonacci’

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
Advertisements

Membuat deret Fibonacci

Penjelasan lebih lengkap mengenai angka Fibonacci dapat dibaca di sini. 2 angka pertama adalah tetap yaitu 0 dan 1, angka berikutnya merupakan penjumlahan 2 angka sebelumnya. 2 kode berikut akan menampilkan n deret Fibonacci, dimana n didapat dari inputan. Read more…

Categories: JAVA Tags: ,