Fraction
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 201 Accepted Submission(s): 129
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
Source
题意:就是给出a数组b数组计算题目中给的式子的答案。
思路:直接暴力,然而思维不清晰数学蒟蒻于是推了半天如何写循环也是醉了2333
#include <iostream>
#include <string.h>
#include <algorithm>
#include <math.h>
using namespace std;
int a[10];
int b[10];
int gcd(int a,int b){
return b==0?a:gcd(b,a%b);
}
int main(){
int t;
scanf("%d",&t);
for(int cas=1;cas<=t;cas++){
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
for(int i=1;i<=n;i++)
scanf("%d",&b[i]);
if(n==1){
int p=b[1]/gcd(b[1],a[1]);
int q=a[1]/gcd(b[1],a[1]);
printf("Case #%d: %d %d\n",cas,p,q);
}
else{
int sum1=a[n]*b[n-1];
int sum2=a[n]*a[n-1]+b[n];
int k=gcd(sum1,sum2);
sum1/=k;
sum2/=k;
int p=sum1;
int q=sum2;
for(int i=n-2;i>=1;i--){
sum1=b[i]*q;
sum2=a[i]*q+p;
k=gcd(sum1,sum2);
p=sum1/k;
q=sum2/k;
}
printf("Case #%d: %d %d\n",cas,p,q);
}
}
return 0;
}