使用二维数组的第n个斐波那契数



我该怎么做呢?我需要创建一个Fibonacci类,其中一个next()方法返回下一个Fibonacci字符串值。后续调用应返回:0、1、1、2、3、5、8等。

程序从用户处获取一个整数,并返回指定数目的字符串值。计算应该使用数组。

public class Fibonacci {
final long[][] A = {{1, 1}, {1, 0}};
public static void  main(String[] args) {
System.out.print("Enter the n th word of the sequence: ");
long n = initialStatement(readValue());
Fibonacci f = new Fibonacci();
for (int i = 0; i < n; i++) {
long[][] b = f.next();
System.out.print(b[0][1]);
}
}

public static long readValue() {
Scanner scanner = new Scanner(System.in);
return scanner.nextLong();
}
public static long initialStatement(long n) {
do {
if (n == 0 || n == 1) {
return n;
} else if (n < 0) {
System.out.print("Wrong value, please enter correct value: ");
n = Fibonacci.readValue();
}
} while (n < 0);
return n;
}
public long[][] next() {
long[][] a =new long[2][2];

for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
a[i][j] += a[i][j] * A[j][i];
}
}
return a ;
}
}

你的矩阵很混乱。

这是一个简单的代码修改,用两个int代替矩阵。

测试一下,然后告诉我。

public class Fibonacci {
long i = -1; // clone of the loop counter i
long fibo1 = 1;
long fibo2 = 1;
public  void  main(String[] args) {
System.out.print("Enter the n th word of the sequence: ");
long n = initialStatement(readValue());
Fibonacci f = new Fibonacci();
for (int i = 0; i < n; i++) {
System.out.print(f.next());
}
}

public static long readValue() {
Scanner scanner = new Scanner(System.in);
return scanner.nextLong();
}
public static long initialStatement(long n) {
do {
if (n == 0 || n == 1) {
return 1; // fibo(0) == fibo(1) == 1
} else if (n < 0) {
System.out.print("Wrong value, please enter correct value: ");
n = Fibonacci.readValue();
}
} while (n < 0);
return n;
}
public String next() {
i++; // simulation of loop i because it is not a param of next()
if(i >= 2) {
long aux = fibo1 + fibo2;
fibo1 = fibo2;
fibo2 = aux;
}
return ""+ fibo2;
}
}

斐波那契数列可以用:

fibo(0) = 0
fibo(1) = 1
fibo(n) = fibo(n - 1) + fibo(n - 2)
在代码中,最简单的实现不使用矩阵。你可以在你的类中这样做:
private int a = 0;
private int b = 0;
public void next() {

// Special case: Return 0 as first number in the sequence.
if(a == 0 && b == 0) {
b = 1;
return 0;
}
// Return the sum of the last two numbers, and store the new last two numbers in a and b.
int result = a + b;
a = b;
b = result;
return result;
}

返回从0开始的斐波那契数列。

最新更新