Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining whether a number is a Fibonacci number

Tags:

java

fibonacci

I need to to write a Java code that checks whether the user inputed number is in the Fibonacci sequence.

I have no issue writing the Fibonacci sequence to output, but (probably because its late at night) I'm struggling to think of the sequence of "whether" it is a Fibonacci number. I keep starting over and over again. Its really doing my head in.

What I currently have is the nth.

public static void main(String[] args)
{
    ConsoleReader console = new ConsoleReader();

    System.out.println("Enter the value for your n: ");
    int num = (console.readInt());
    System.out.println("\nThe largest nth fibonacci: "+fib(num));
    System.out.println();
}

static int fib(int n){
    int f = 0;
    int g = 1;
    int largeNum = -1;
    for(int i = 0; i < n; i++)
    {
      if(i == (n-1))
          largeNum = f;
      System.out.print(f + " ");
      f = f + g;
      g = f - g;
    }
    return largeNum;
}
like image 714
Emily Avatar asked Jun 29 '10 10:06

Emily


People also ask

How do you check if a number is a Fibonacci number python?

num=int(input("Enter the number you want to check\n")) temp=1 k=0 a=0 summ=0 while summ<=num: summ=temp+k temp=summ k=temp if summ==num: a=a+1 print("Yes. {} is a fibonnaci number".

How do you prove the Fibonacci sequence?

fn = fn−1 + fn−2 . We call this a recurrence since it defines one entry in the sequence in terms of earlier entries. And it gives the Fibonacci numbers a very simple interpretation: they're the sequence of numbers that starts 1, 1 and in which every subsequent term in the sum of the previous two.

Can any number be a Fibonacci number?

Here is a longer list: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, ...


Video Answer


1 Answers

Read the section titled "recognizing fibonacci numbers" on wikipedia.

Alternatively, a positive integer z is a Fibonacci number if and only if one of 5z^2 + 4 or 5z^2 − 4 is a perfect square.[17]

Alternatively, you can keep generating fibonacci numbers until one becomes equal to your number: if it does, then your number is a fibonacci number, if not, the numbers will eventually become bigger than your number, and you can stop. This is pretty inefficient however.

like image 59
IVlad Avatar answered Dec 04 '22 23:12

IVlad