Viết phương thức tính số Fibonacci thứ N

Yêu cầu:
Một dãy Fibonacci có dạng như sau : 1, 1, 2, 3, 5, 8, 13, 21…, dãy trên bắt đầu bởi 2
số 1 và 1, các số sau bằng tổng của 2 số trước liền kề.
a. Viết phương thức đệ quy tính số thứ n của dãy Fibonacci : ví dụ fibo(4) = 3;
b. Tương tự câu a nhưng không sử dụng đệ quy

a. Viết phương thức đệ quy tính số thứ n của dãy Fibonacci : ví dụ fibo(4) = 3;

/*********************************************
 * Author: VietVH
 * Date: 11/07/2016
 *********************************************/

package vncoding;

import java.util.Scanner;

public class JavaCore {
	public static void main(String args[]) {
		int n;

		Scanner sc = new Scanner(System.in);
		do{
			System.out.print("n = ");
			n = sc.nextInt();
		}while(n <= 0);
		
		// print out the Fibonacci
		System.out.format("%dth Fibonacci is: %d", n, fibo(n));

	}
	public static int fibo(int n){
		if(n == 1 || n == 2){
			return 1;
		}
		else{
			return(fibo(n-2) + fibo(n-1));
		}
	}
}

b. Tương tự câu a nhưng không sử dụng đệ quy

/*********************************************
 * Author: VietVH
 * Date: 11/07/2016
 *********************************************/

package vncoding;

import java.util.Scanner;

public class JavaCore {
	public static void main(String args[]) {
		int n;

		Scanner sc = new Scanner(System.in);
		do{
			System.out.print("n = ");
			n = sc.nextInt();
		}while(n <= 0);
		
		//print out the Fibonacci
		System.out.format("%dth Fibonacci is: %d", n, fibo(n));

	}
	public static int fibo(int n){
		int cnt = 2;
		int a0 = 1, a1 = 1, a2 = 2;
		if(n == 1 || n == 2){
			return 1;
		}
		else{
			while(cnt++ < n){
				a2 = a0 + a1;
				a0 = a1;
				a1 = a2;
			}
			return a2;
		}
	}
}

Kết quả:

Java - Tìm số Fibonacci thứ n
Java – Tìm số Fibonacci thứ n

Be the first to comment

Leave a Reply