Home > JAVA > Membuat deret Fibonacci

Membuat deret Fibonacci

Penjelasan lebih lengkap mengenai angka Fibonacci dapat dibaca di sini. 2 angka pertama adalah tetap yaitu 0 dan 1, angka berikutnya merupakan penjumlahan 2 angka sebelumnya. 2 kode berikut akan menampilkan n deret Fibonacci, dimana n didapat dari inputan.


public class TryFibonanacciNonRekursif {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Masukan banyak deret Fibonacci yang diinginkan: ");
int n = sc.nextInt();
printFibo(n);
}
public static void printFibo(int n){
int a = 0;
int b = 1;
int c = 0;
System.out.print(a + ", " + b);
for(int i=1; i<=n-2; i++){
c = a + b;
a = b;
b = c;
System.out.print(", " + c);
}
}
}

public class TryFibonacciRekursif {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Masukan banyak deret Fibonacci yang diinginkan: ");
int n = sc.nextInt();
System.out.print(0 + ", " + 1);
for(int i=3; i<n; i++){
System.out.print(", " + doFibo(i));
}
}
public static int doFibo(int n){
if(n==0)
return 0;
else if(n==1)
return 1;
else
return doFibo(n-1) + doFibo(n-2);
}
}

Categories: JAVA Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: