博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【Java SE】斐波那契数列
阅读量:4625 次
发布时间:2019-06-09

本文共 1953 字,大约阅读时间需要 6 分钟。

首先是最简单的方式

1 public class Fabonacci { 2     //1 1 2 3 5 8... 3         static int i = 0; 4     static int j = 0; 5     static int f(){ 6         if(j==0){ 7             j = 1; 8             return 1; 9         }10         int r = i + j;11         i = j;12         j = r;13         return r;14     }15     public static void main(String[] args) {16         for (int i = 0; i < 18; i++) {17             System.out.print(f()+" ");18         }19     }20 }

输出如下:

1 1 2 3 5 8 13 21 34 55 

 

然后是使用递归

package com.knowind;public class Fabonacci {    //1 1 2 3 5 8...    int count = 0;    Integer next(){        return g(count);    }    int g(int count){        this.count++; //        if(count < 2){            return 1;        }        //0>1 1>1 2>2 3>3 4>5 5>8        return g(count-1)+g(count-2);//前一次的次数加上前前一次的次数    }    public static void main(String[] args) {        Fabonacci f = new Fabonacci();        for (int i = 0; i < 10; i++) {            System.out.print(f.next()+" ");        }    }}

输出:

1 1 2 8 10946 Exception in thread "main" java.lang.StackOverflowError    at com.knowind.Fabonacci.g(Fabonacci.java:15)    at com.knowind.Fabonacci.g(Fabonacci.java:15)

来看看为什么会出现这样的情况。事实上,拿 this.count = 8 来举例,刚进来 g( int count )方法, this.count 便 this.count++ 变成了 this.count = 9,随后 ,在 return 的时候,又调用 g( count-1 ) 即 g( 8 )!这不就是陷入了死循环吗?

那么怎么修正呢?

public class Fabonacci {    //1 1 2 3 5 8...    int count = 0;    Integer next(){        return g(count++);    }    int g(int count){//        this.count++;         if(count < 2){            return 1;        }        //0>1 1>1 2>2 3>3 4>5 5>8        return g(count-1)+g(count-2);//前一次的次数加上前前一次的次数    }    public static void main(String[] args) {        Fabonacci f = new Fabonacci();        for (int i = 0; i < 10; i++) {            System.out.print(f.next()+" ");        }    }}

题外话:g( count++) 先为方法形参赋值再对 count+1,这一点和 g( ++count ) 情形相反。

输出如下:

1 1 2 3 5 8 13 21 34 55 

转载于:https://www.cnblogs.com/Tsing-Evan/p/8446002.html

你可能感兴趣的文章
JAVA wait(), notify(),sleep具体解释
查看>>
数据挖掘十大经典算法
查看>>
WebService原理
查看>>
【Unity 3D】学习笔记三十七:物理引擎——碰撞与休眠
查看>>
js动态删除div元素
查看>>
计算机网络中的TCP/IP模型
查看>>
spring mvc 自定义Handlermapping
查看>>
JS验证密码安全级别
查看>>
Cookie是可以覆盖的,如果重复写入同名的Cookie,那么将会覆盖之前的Cookie。
查看>>
Django Models的数据类型
查看>>
博客之初体验-----python初了解
查看>>
jquery.fileupload插件 ie9下不支持上传
查看>>
6.1 HTML5的框架
查看>>
Nginx的500,502,504错误解决方法
查看>>
SAP MM MM17里不能修改物料主数据'Purchasing Value Key'字段值?
查看>>
python 基础语法知识(一)
查看>>
ssh整合
查看>>
大数组分时加载算法 timedChunk
查看>>
leetcode -- 11. 盛最多水的容器
查看>>
vim vimtutor
查看>>