题面
求下列多项式前k项的和,1 - 1/2 + 2/3 - 3/4 +4/5 - 5/6 + ...
要求结果表示为真分式形式
输入
输入k,k<=100
输出
求前k项的和
样例输入
2
样例输出
1/2
代码
import java.util.Scanner; public class Main { public static long GCD(long a, long b) { if(b == 0) { return a; } return GCD(b,a % b); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int k = sc.nextInt(); double sum = 1; long son = 1, mother = 1; if(k == 1) { System.out.println("1/1"); System.exit(-1); } for(int i = 2; i <= k; ++i) { if (i % 2 == 0) { long x= son * i - mother *(i - 1); //新的分子 long y = mother * i; //新的分母 long gcd = GCD(x, y); //最大公因数 son = x / gcd; mother = y / gcd; } else { long x = son * i + mother * (i - 1); long y = mother * i; long gcd = GCD(x, y); son = x / gcd; mother = y / gcd; } } System.out.println(son + "/" + mother); } }
Comments NOTHING