zoukankan      html  css  js  c++  java
  • (斐波那契总结)Write a method to generate the nth Fibonacci number (CC150 8.1)

    根据CC150的解决方式和Introduction to Java programming总结:

    使用了两种方式,递归和迭代

    CC150提供的代码比较简洁,不过某些细节需要分析。

    现在直接运行代码,输入n(其中用number代替,以免和方法中的n混淆)的值,可以得出斐波那契数。

    代码如下:

    /*  CC150 8.1
        Write a method to generate the nth Fibonacci number
        Author : Mengyang Rao
        note : Use two methods ,Iteration and Recursion
        Date : 2015-02-25 23:56:00
    */
    
    
    import java.util.Scanner;
    public class TestFibonacci {
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            System.out.print("Please enter n :");
            int number = input.nextInt();
            System.out.println("The Iteration number is : " + fibonacci(number) + "
     n value is : " + number);
            System.out.println("The Recursion number is : " + fibo(number) + "
     n value is : " + number);
        }
    // Version: Recursion
        public static long fibo(long n ) {
        if(n == 0) 
            return 0;
        else if (n == 1)
            return 1;
        else if (n > 1)
            return fibo(n - 1) + fibo(n - 2);
        else 
            return -1;
    }
    //  Version: Iteration
        public static long fibonacci(long n) {
            int a = 0, b = 1;
            if (n < 0) 
                return -1;
            else if (n == 0)
                return 0;
            for (int i = 3; i <= n; i++) {
                int c = a + b;
                a = b;
                b = c;
            }
            return b;
        }
    }
  • 相关阅读:
    第十一章 练习。内附100道练习题URL
    第八章 模块;第九章 文件
    mysql union和join 的使用
    第七章 循环
    第六章 课后习题
    第六章 字符串操作
    第五章 课后习题
    第五章 容器之字典
    实战智能推荐系统笔记
    协同过滤推荐算法的原理及实现
  • 原文地址:https://www.cnblogs.com/raomengyang/p/4300472.html
Copyright © 2011-2022 走看看