天天看點

48.求斐波那契分數數列之和

程式設計題目:

48.有一分數序列:2/1,3/2,5/3,8/5,13/8,21/13… 求出這個數列的前20項之和。

示例代碼:

package program.calculation.exercise48;

import java.util.Scanner;

/**
* 48.有一分數序列:1/2,2/3,3/5,5/8,8/13,13/21... 求出這個數列的前20項之和。
* 分析:注意分子與分母的變化規律:分子和分母分别是一組斐波那契數列,即每一項等于前兩項的和。
*/

public class FractionSum {
	public static void main(String[] args) {
		
		System.out.println("請輸入數列的項數n:");
	    @SuppressWarnings("resource")
		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		
		System.out.println("第一種方式(循環):");
		double sum1 = loopFraction(n);
		System.out.println("數列前"+n+"項的和是:"+sum1);
		
		System.out.println("第二種方式(遞歸):");
		double sum2 = recurFraction(n);
		System.out.println("數列前"+n+"項的和是:"+sum2);
 
	}
	
	//第一種方式:循環求出分子分母比值,再相加
	private static double loopFraction(int n) {
		
		double molecule = 1; //分子
		double denominator = 1; //分母
		double fraction = molecule/denominator; //分數值
		double sum = 0; //數列前n項之和
		
		for(int i=1; i<=n; i++){
			double temp1 = molecule;
			double temp2 = denominator;
			molecule = temp1+temp2;
			denominator = temp1;
		    fraction = molecule/denominator;
		    sum += fraction; 
		}
		return sum;
		
	}	
	
	//第二種方式:遞歸分别求分子分母,再相除
	private static double recurFraction(int n) {
		
		double sum = 0;
		for (int i=1; i<=n; i++) {
			sum += (double)(recurMolecule(i)/recurDenominator(i));
		}
		return sum;
	}
	
	//遞歸求分子
	private static double recurMolecule(int n) {
		
		double molecule = 0;
		if(1 == n) {
			molecule = 2;
		}else if(2 == n) {
			molecule = 3;
		}else {
			molecule = recurMolecule(n-1) + recurMolecule(n-2);
		}
		return molecule;
		
	}
	
	//遞歸求分母
	private static double recurDenominator(int n) {
		
		double denominator = 0;
		if(1 == n) {
			denominator = 1;
		}else if(2 == n) {
			denominator = 2;
		}else {
			denominator = recurDenominator(n-1) + recurDenominator(n-2);
		}
		return denominator;
		
	}
	
}
           

結果顯示:

48.求斐波那契分數數列之和