아래 처럼 피보나치(Fibonacci) 수 테이블을 출력하는 Java 소스이다.

------------------------------------------------- n F(n) ------------------------------------------------- 0 0 10 55 20 6,765 30 832,040 40 102,334,155 50 12,586,269,025 60 1,548,008,755,920 70 190,392,490,709,135 80 23,416,728,348,467,685 90 2,880,067,194,370,816,120 100 354,224,848,179,261,915,075 110 43,566,776,258,854,844,738,105 120 5,358,359,254,990,966,640,871,840 130 659,034,621,587,630,041,982,498,215 140 81,055,900,096,023,504,197,206,408,605 150 9,969,216,677,189,303,386,214,405,760,200 -------------------------------------------------



 

* Java 소스

// Filename: MakeFibonacciTable_01.java
//
//        1) Show a simple table of Fibonacci numbers.
//        2) Use a linear recursion whose time complexity is o(N).
//
//   Compile: javac MakeFibonacciTable_01.java
//   Execute: java MakeFibonacciTable_01
//
//   Date: 2013. 3. 14.
//  Author: pkim __AT__ scripts ((DOT)) pe ((DOT)) kr

import java.math.*;

public class MakeFibonacciTable_01 {

    private static String toCurrencyString(BigInteger x) {
     String s = x.toString();
     int n = s.length();
     int i = 0;
     if (n <= 3) {
      return s;
     }
     String t = "";
     i = n % 3;
     if (i > 0 && n > 3) {
         t = s.substring(0, n % 3) + ",";
     }
     while (i < n - 3) {
          t += s.substring(i, i + 3) + ",";
          i += 3;
        }
       t += s.substring(i, n);
     return t;
    }

    private static BigInteger fib_aux(int n, int i, BigInteger a, BigInteger b) {
        if (i == 0) {
            return a;
        }
        else {
            BigInteger t = a.add(b);
            a = b;
            b = t;
            return fib_aux(n, i - 1, a, b);
        }
    }

    public static BigInteger fibo1(int n) {
        return fib_aux(n, n, new BigInteger("0"), new BigInteger("1"));
    }
   

     public static void main(String[] args) {
         BigInteger value;
         int i;

         System.out.printf("---------------------------------------------------------\n");
         System.out.printf("   n                                               F(n)    \n");
         System.out.printf("---------------------------------------------------------\n");
         for (i = 0; i <= 150; i++) {
             value = fibo1(i);
             if ((i % 10) == 0) {
                 System.out.printf("%5d   %47s\n", i, toCurrencyString(value));
             }
         }
         System.out.printf("----------------------------------------------------------\n");
         System.out.printf("\n");
    }
}

 

 

 

Posted by Scripter
,