package com.yuxi.day22;
import java.util.ArrayList;
public class SumTest1 {
/*
* 题目:有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13... 求出这个数列的前20项之和
*/
public static ArrayList<Integer> fzList = new ArrayList<Integer>();
public static ArrayList<Integer> fmList = new ArrayList<Integer>();
public static void main(String[] args) {
fenSuSum(20);
}
public static int fz(int n) {
if (n == 1) {
return 2;
} else if (n == 2) {
return 3;
} else
return fz(n - 1) + fz(n - 2);
}
public static int fm(int n) {
if (n == 1) {
return 1;
}
else if (n == 2) {
return 2;
} else
return fm(n - 1) + fm(n - 2);
}
public static void addArr(int n) {
for (int i = 1; i <= n; i++) {
fzList.add(SumTest1.fz(i));
fmList.add(SumTest1.fm(i));
}
}
public static void pintArr(int n) {
addArr(n);
for (int i = 0; i < fzList.size(); i++) {
if (i != fzList.size() - 1) {
System.out.print(fzList.get(i) + "/" + fmList.get(i) + "+");
} else
System.out.print(fzList.get(i) + "/" + fmList.get(i));
}
}
public static void fenSuSum(int n) {
pintArr(n);
double fzs;
double fmJi = 1;
double fzSum = 0;
Object[] fzArr = fzList.toArray();
Object[] fmArr = fmList.toArray();
for (int i = 0; i < fmArr.length; i++) {
long fm = Long.parseLong(fmArr[i].toString());
fmJi *= fm;
}
for (int i = 0; i < fzArr.length; i++) {
long fz = Long.parseLong(fzArr[i].toString());
long fm = Long.parseLong(fmArr[i].toString());
fzs = fz * (fmJi / fm);
fzSum += fzs;
}
while (fmJi > Integer.MAX_VALUE) {
fmJi /= 10;
fzSum /= 10;
}
long fmJiLong = (long) fmJi;
long fzSumLong = (long) fzSum;
int x = 2;
while (x <= 10) {
if (fmJiLong % x == 0 && fzSumLong % x == 0) {
fmJiLong /= x;
fzSumLong /= x;
x = 2;
} else
x++;
}
System.out.print("=" + fzSumLong + "/" + fmJiLong);
System.out.println("=" + (double) ((double)fzSumLong / fmJiLong));
}
}
|