Java、斐波那契数列遍历器

 

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;
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值