Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In java, how would I find the nth Fibonacci number?

Determining the Fibonacci sequence is easy enough to figure out:

int num = 0;
int num2 = 1;
int loop;
int fibonacci;
System.out.print(num2);
for (loop = 1; loop <= 10; loop ++)
{
    fibonacci = num + num2;
    num = num2;
    num2 = fibonacci;
    System.out.print(" " + fibonacci);
}

My problem lies with trying to pinpoint the value for a specified N. As in, If I want to find the 6th element in the sequence, which is 8, how would I find that number, and only that number?

like image 518
CydonPrax Avatar asked Oct 22 '12 22:10

CydonPrax


2 Answers

In your code, num starts as the 0th Fibonacci number, and num1 as the 1st. So to find the nth, you have to iterate the step n times:

for (loop = 0; loop < n; loop ++)
{
    fibonacci = num + num2;
    num = num2;
    num2 = fibonacci;
}
System.out.print(num);

and only print it when you've finished.

When the loop counter loop has the value k, num holds the kth Fibonacci number and num2 the (k+1)th.

like image 71
Daniel Fischer Avatar answered Sep 25 '22 20:09

Daniel Fischer


To find the n'th digit, we need to know the length of the Fibonacci numbers. You can convert int to string using Java's Integer.toString(int) function. Using the string, one can then determine the length of the converted Fibonacci number.

EDIT: Removed code b/c likely hwk question

like image 25
ehuang Avatar answered Sep 25 '22 20:09

ehuang