Herzlich Willkommen

Live processing contents

Friday, October 8, 2010

JAVA Fibonacci in general

 HASIL EXECUTE :
 init:
deps-jar:
compile:
run:
fib(1) = 1
fib(2) = 1
fib(3) = 2
fib(4) = 3
fib(5) = 5
fib(6) = 8
fib(7) = 13
fib(8) = 21
fib(9) = 34
BUILD SUCCESSFUL

BERIKUT SYNTACS JAVA-nya :

import javax.swing.JOptionPane;
 
 /*
    This program computes Fibonacci numbers using a recursive
    method.
  */
 public class Fibonacci

    public static void main(String[] args)
    { 
       String input = JOptionPane.showInputDialog("Enter n: ");
       int n = Integer.parseInt(input);
 
       for (int i = 1; i <= n; i++)
       {
          int f = fib(i);
          System.out.println("fib(" + i + ") = " + f);
       }
       System.exit(0);
      
    }
 
    /**
       Computes a Fibonacci number.
       @param n an integer
       @return the nth Fibonacci number
    */
    public static int fib(int n)
    { 
       if (n <= 2)
            return 1;
       else
            return fib(n - 1) + fib(n - 2);
    }
 }

Silakan dicoba

No comments:

Post a Comment