求斐波那契数列的5种实现--JavaEE23,xuef

斐波那契数列 1,1,2,3,5,8,13,21....
通项公式 fib(n) = fib(n-1) + fib(n-2)
1. 普通迭代
...
2. 普通递归

[Java] 纯文本查看 复制代码

?

1

2

3

private static long fib(int n){

    return n<=2?1:(fib(n-1)+fib(n-2));

}



3. 带缓存的递归
        

[Java] 纯文本查看 复制代码

?

1

2

3

4

5

6

7

8

9

static Map<Integer,Long> cache2 = new HashMap<>();

        private static long fib2(int n){

        if(n <= 2) return 1L;

        if(cache2.containsKey(n))

            return cache2.get(n);

        Long fibn = fib2(n-1)+fib2(n-2);

        cache2.put(n, fibn);

        return fibn;

    }



4. 使用 BigInteger 防止溢出

[Java] 纯文本查看 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

static Map<Integer, BigInteger> cache = new HashMap<>();

    public static void main(String[] args) {

        int n = 100;

        BigInteger bi = fib(n);

        System.out.println(bi);

    }

 

    private static BigInteger fib(int n) {

        if(n <= 2) return BigInteger.ONE;

        if(cache.containsKey(n))

            return cache.get(n);

         

        BigInteger t = new BigInteger(fib(n-1).toByteArray()).

                add(new BigInteger(fib(n-2).toByteArray()));

        cache.put(n, t);

        return t;

    }


5. 斐波那契数列迭代器

[Java] 纯文本查看 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

/**

 * 定义一个遍历器,用于遍历斐波那契数字。

 *

 * @author moveb

 *

 */

public class T24_13_FibonacciIterator implements Iterator<Integer> {

    private int upBound = 23302;

    private int pre = 1;

    private int cur = 1;

     

    public T24_13_FibonacciIterator(){}

     

    public T24_13_FibonacciIterator(int ub){

        upBound = ub;

    }

     

    @Override

    public boolean hasNext() {

        return (cur < upBound);

    }

 

    @Override

    public Integer next() {

        int fib = cur;

        cur = cur + pre;

        pre = fib;

        return fib;

    }

 

    @Override

    public void remove() {

         

    }

}

发布了896 篇原创文章 · 获赞 10 · 访问量 3万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览