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

∥☆過路亽.° 提交于 2019-12-05 01:27:50

问题


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?


回答1:


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.




回答2:


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




回答3:


int n=5;//position of the fibonacci number to find
int fibonacci=0,num=0,num2=1;
for(int loop=1;loop<n;loop++)
{
   fibonacci=num+num2;
   num=num2;
   num2=fibonacci;
}
System.out.println(num);



回答4:


import java.util.Scanner;
public class fibonacci{
public static void main(String[]args){
    Scanner i=new Scanner(System.in);
    String n=System.getProperty("line.separator");

    int count=0,x=0,y=1,sum;

    System.out.println("Enter a number:  ");
    int n=i.nextInt();

    for(count=0;count<n;count++){
        System.out.print(" "+ x);
        sum=x+y;
        x=y;
        y=sum;
    }
  }
}



回答5:


import acm.program.*;

public class FibonacciToN extends ConsoleProgram {

    public void run() {

        println("This program will display a table of Fibonacci numbers up to value n.");
        int n = readInt("Enter an integer for value n: ");
        int result = sequence(n);  

    }

    private int sequence(int n) {

        int a = 0;
        int b = 1;

        while (a < n) {  
            println(a); 
            a = a + b;
            b = a - b;
            }

        return a;
    }
}


来源:https://stackoverflow.com/questions/13021102/in-java-how-would-i-find-the-nth-fibonacci-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!