package list;
import java.math.BigInteger;
import java.util.Iterator;
/**
* @author: xyz
* @create: 2022/8/19
* @Description:
* @FileName: Exercise24_13
* @History:
* @自定义内容:
*/
public class Exercise24_13 {
public static void main(String[] args) {
FibonacciIterator iterator = new FibonacciIterator(10_0000L);
while (iterator.hasNext())
System.out.print(iterator.next() + " ");
}
/** 斐波那契数列迭代器 */
static class FibonacciIterator implements Iterator<BigInteger> {
private BigInteger f0 = BigInteger.ZERO;
private BigInteger f1 = BigInteger.ONE;
private BigInteger currentValue = BigInteger.ZERO; //当前值
private BigInteger maxValue; //最大值
private int nextIndex; //索引
public FibonacciIterator(long maxValue) {
this.maxValue = BigInteger.valueOf(maxValue);
}
@Override
public boolean hasNext() {
currentValue = fab();
return currentValue.compareTo(maxValue) <= 0;
}
@Override
public BigInteger next() {
nextIndex++;
return currentValue;
}
/** 返回斐波那契数 */
private BigInteger fab() {
if (nextIndex == 0) currentValue = f0;
else if (nextIndex == 1 || nextIndex == 2) currentValue = f1;
else {
f0 = f1;
f1 = currentValue;
currentValue = f0.add(f1);
}
return currentValue;
}
}
}