Fraction
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1045 Accepted Submission(s): 468
Problem Description
Mr. Frog recently studied how to add two fractions up, and he came up with an evil idea to trouble you by asking you to calculate the result of the formula below:

As a talent, can you figure out the answer correctly?

As a talent, can you figure out the answer correctly?
Input
The first line contains only one integer T, which indicates the number of test cases.
For each test case, the first line contains only one integer n (n≤8).
The second line contains n integers: a1,a2,⋯an(1≤ai≤10).
The third line contains n integers: b1,b2,⋯,bn(1≤bi≤10).
For each test case, the first line contains only one integer n (n≤8).
The second line contains n integers: a1,a2,⋯an(1≤ai≤10).
The third line contains n integers: b1,b2,⋯,bn(1≤bi≤10).
Output
For each case, print a line “Case #x: p q”, where x is the case number (starting from 1) and p/q indicates the answer.
You should promise that p/q is irreducible.
You should promise that p/q is irreducible.
Sample Input
1 2 1 1 2 3
Sample Output
Case #1: 1 2HintHere are the details for the first sample: 2/(1+3/1) = 1/2
题意:给出两个数列a[ ], b[ ];按图中式子计算,要求结果最简,用到了辗转相除法求最大公约数;
看看代码就懂了:
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
int aa(int a, int b){ //求最大公约数;
if(a<b){
a=a+b;
b=a-b;
a=a-b;
}
return a%b==0?b:aa(b, a%b);
}
int main(){
int T;
cin >> T;
int cnt=0;
while(T--){
cnt++;
int n;
cin >> n;
int a[10], b[10];
for(int i=1; i<=n; i++)
cin >> a[i];
for(int i=1; i<=n; i++)
cin >> b[i];
int x=a[n], y=b[n]; //x是分母, y是分子;
while(n>1){
n--;
int temp=x;
x=temp*a[n]+y;
y=b[n]*temp;
}
int c=aa(x, y);
cout << "Case #" << cnt << ": " << y/c << ' ' << x/c << endl;
}
return 0;
}
本文介绍了一个编程挑战,任务是计算一系列分数的复杂表达式的最简形式。通过输入两个整数数组,代表分数的分子和分母,利用辗转相除法找到结果的最简形式。

348

被折叠的 条评论
为什么被折叠?



