其他分享
首页 > 其他分享> > Fraction(HDU-5912)

Fraction(HDU-5912)

作者:互联网

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 (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.
Sample Input

1
2
1 1
2 3

Sample Output
Case #1: 1 2
这个题就是从下往上算,每次把分子分母的结果保存下来,不要计算分式的值,最后求分子,分母的最大公约数,然后输出就可以了。

#include<stdio.h>
int gcd(int a,int b)
{
	if(a%b==0)
		return b;
	else
	{
		return gcd(b,a%b);
	}
}
int main()
{
	int i,j,n,m,a[200],b[200],t,ansa,ansb,temp,r=0;
	scanf("%d",&t);
	while(t--)
	{
		r++;
		scanf("%d",&n);
		for(i=1;i<=n;i++)
			scanf("%d",&a[i]);
		for(i=1;i<=n;i++)
			scanf("%d",&b[i]);
		ansa=b[n];
		ansb=a[n];
		for(i=n-1;i>=1;i--)
		{
			temp=ansb;
			ansb=ansb*a[i]+ansa;
			ansa=temp*b[i];
		}
		m=gcd(ansa,ansb);
		printf("Case #%d: %d %d\n",r,ansa/m,ansb/m);
	}
	return 0;
 } 

标签:HDU,return,int,contains,Fraction,ansa,ansb,line,5912
来源: https://blog.csdn.net/weixin_44313771/article/details/100030384