【程序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);
}
}
网友评论