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;
        }
    }
  • 相关阅读:
    关于TFS中WorkItem的探究
    Pro Android4 面试题归纳
    truncate 、delete、drop
    获取数据库中所有表的行数及其他信息
    【转】高手速成android开源项目【View篇】
    Can't create handler inside thread that has not called Looper.prepare()解决办法
    Android使用获取HTML
    .net操作EXCEL
    ASP.NET发送邮件
    如何使用 MasterPage
  • 原文地址:https://www.cnblogs.com/raomengyang/p/4300472.html
Copyright © 2011-2022 走看看