[英]Code to print Nth fibonacci number
所以這是我的賦值,我必須編寫一個函數,該函數接受一個小於100的數字,並在該位置返回fibonacci元素。 我不明白我的代碼有什么問題。 請注意,我只寫了getFibonacciElementAt
函數代碼
import java.util.Scanner;
public class FibonacciNumber {
public long getFibonacciElementAt(int index) {
Scanner sc= new Scanner(System.in);
System.out.println("Please enter the number");
int n= sc.nextInt();
if(n<0)
return -1;
int a=0;
int b=1;
int i;
for(i=2; i<=n; i++)
{
int temp=a;
a=b;
b=temp;
}
return a;
}
public void printFibonacciElementAt(int index) {
System.out.println(getFibonacciElementAt(index));
}
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Exactly 1 inputs required.");
return;
}
try {
int num = Integer.parseInt(args[0]);
FibonacciNumber obj = new FibonacciNumber();
obj.printFibonacciElementAt(num);
} catch (NumberFormatException e) {
System.out.println("Only integers allowed.");
}
}
}
好的,因此請使用備忘錄重新發布更好的遞歸版本,以使n <= 100的運行時少於1秒:
public static long getFibonacciElementAt(int n, long[] d) {
if (n == 0 || n == 1)
return n;
if (d[n] == 0)
d[n] = getFibonacciElementAt(n - 1, d) + getFibonacciElementAt(n - 2, d);
return d[n];
}
但是,一旦調用該方法,只需傳遞一個大小為n + 1的新數組,如下所示:
System.out.println(getFibonacciElementAt(n, new long[n+1]));
您只是交換而不是將前兩個數字相加。 因此,請嘗試以下操作:
int a=0;
int b=1;
int temp;
for(int i=2; i<=n; i++)
{
temp=a+b;
a=b;
b=temp;
}
return b;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.