package fibonacci;
import java.math.BigInteger;
import java.math.*;
public class fibo {
public static void main(String[] args) {
//number of elements to generate in a series
BigInteger sum;
BigInteger[] series= new BigInteger[4000000];
//long[] series = new long[4000000];
//create first 2 series elements
series[0] = BigInteger.valueOf(1);
series[1] = BigInteger.valueOf(2);
//create the Fibonacci series and store it in an array
for(int i=2; i < series.length; i++){
series[i] = series[i-1].add(series[i-2]);
if (series[i].mod(BigInteger.valueOf(2)) == BigInteger.valueOf(0)){
sum = sum.add(series[i]); //error here
}
}
System.out.println("Fibonacci Series sum " + sum); //error here
}
}
我正在尝试计算斐波纳契的偶数和。我需要在这里更改什么? 或者是否应该使用.subtract重写整个程序?
答案 0 :(得分:7)
初始化sum
(对BigInteger的引用)。局部变量不会获得默认值。你必须自己初始化它们。
BigInteger sum= new BigInteger("0");
或
BigInteger sum= BigInteger.ZERO;
答案 1 :(得分:1)