Fraction

来源:互联网 发布:poser pro 是什么软件 编辑:程序博客网 时间:2024/05/29 07:17
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?
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 (n8n≤8). 

The second line contains n integers: a1,a2,an(1ai10a1,a2,⋯an(1≤ai≤10). 
The third line contains n integers: b1,b2,,bn(1bi10)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.
Sample Input
121 12 3
Sample Output
Case #1: 1 2          
Hint
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;}