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;
}
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".
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.
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, ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With