- import java.math.BigDecimal;
- public class FenShuSan {
- /**
- * 有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和,请用分数形式输出最后的结果,如 x/y
- *
- * 递归解决 参数3个int型的变量 除数 被除数 循环次数 当count==1时退出
- */
- public static void main(String[] args) {
- System.out.println("\n和为:"+new FenShuSan().getSum(2.0, 1, 20));
- System.out.println("\n和为:"+new FenShuSan().getSum(2, 1, 20));
- }
- /**
- * @param divisor
- * @param divident
- * @param count
- * @return
- * 根据 count个分数的和
- * 拿传过来的分数的商加上以后所有可能出现的商
- */
- private double getSum(double divisor,double divident,int count){
- System.out.println((int)divisor+"/"+(int)divident);
- if(count==1){
- return divisor/divident;
- }
- double result=divisor/divident;
- double tmp=divisor;
- divisor+=divident;
- divident=tmp;
- return result+(getSum(divisor,divident,--count));
- }
-
- /**
- * @param divisor
- * @param divident
- * @param count
- * @return
- * 算出count个分数中分子和分母的和
- * 拿传过来的分子和分母分别加上以后所有可能出现的分子和分母的和
- */
- private String getSum(int divisor,int divident,int count){
- System.out.println(divisor+"/"+divident);
- if(count==1){
- return divisor+"/"+divident;
- }
- int tmp=divisor;
- divisor+=divident;
- divident=tmp;
- String[] sums=getSum(divisor,divident,--count).split("/");
- return tmp+Integer.parseInt(sums[0])+"/"+(divisor-divident+Integer.parseInt(sums[1]));
- }
-
- }
复制代码 运行结果
2/1
3/2
5/3
8/5
13/8
21/13
34/21
55/34
89/55
144/89
233/144
377/233
610/377
987/610
1597/987
2584/1597
4181/2584
6765/4181
10946/6765
17711/10946
和为:32.660260798641644
2/1
3/2
5/3
8/5
13/8
21/13
34/21
55/34
89/55
144/89
233/144
377/233
610/377
987/610
1597/987
2584/1597
4181/2584
6765/4181
10946/6765
17711/10946
和为:46365/28655
|