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?
For each test case, the first line contains only one integer n ( n≤8 n≤8).
The second line contains n integers: a1,a2,⋯an(1≤ai≤10 a1,a2,⋯an(1≤ai≤10).
The third line contains n integers: b1,b2,⋯,bn(1≤bi≤10) b1,b2,⋯,bn(1≤bi≤10).
You should promise that p/q is irreducible.
1 2 1 1 2 3
Case #1: 1 2
Here are the details for the first sample: 2/(1+3/1) = 1/2
就是按照按照图片上的一步一步的计算。从后往前推。
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; int a[1000],b[1000]; int grc(int a,int b) { if(a%b) return grc(b,a%b); else return b; } int main() { int kk=1; int t,n,m,i,j; scanf("%d",&t); while(t--) { scanf("%d",&n); for(i=1;i<=n;i++) { scanf("%d",&a[i]); } for(i=1;i<=n;i++) { scanf("%d",&b[i]); } int q,p,k; p=a[n];q=b[n]; for(i=n-1;i>0;i--) { k=p; p=p*a[i]+q; q=k*b[i]; } int m=grc(p,q); printf("Case #%d: ",kk); printf("%d %d\n",q/m,p/m); kk++; } return 0; }