【程序20】
題目:有一分數序列:2/1,3/2,5/3,8/5,13/8,21/13...求出這個數列的前20項之和。
package com.share.test11_20;
/**
* 【程序20】題目:<br>
* 有一分數序列:2/1,3/2,5/3,8/5,13/8,21/13...求出這個數列的前20項之和。
*
* @author brx
*/
public class Test20 {
public static void main(String[] args) {
test();
test4();
}
/**
* 思路1:<br>
* 遞歸,兩個遞歸數組之差
*/
public static void test() {
double sum = 0;
for (int i = 1; i <= 20; i++) {
sum += test3(i);
}
System.out.println("數列前20項之和:" + sum);
}
public static double test1(double n) {
double result = 0;
if (n == 1) {
result = 2;
} else if (n == 2) {
result = 3;
} else {
result = test1(n - 1) + test1(n - 2);
}
return result;
}
public static double test2(double n) {
double result = 0;
if (n == 1) {
result = 1;
} else if (n == 2) {
result = 2;
} else {
result = test2(n - 1) + test2(n - 2);
}
return result;
}
public static double test3(double n) {
double result = test1(n) / test2(n);
return result;
}
/**
* 思路2:<br>
* 從第1項開始依次遞變,將結果存進變量中
*/
public static void test4() {
double sum = 0;
double x = 2, y = 1, t = 0;
for (int i = 0; i < 20; i++) {
sum += x / y;
t = x;
x = y + x;
y = t;
}
System.out.println("數列前20項之和為:"+sum);
}
}