- 分数加减乘除。
- 注意精度。
- 注意求最大公约数时的大小关系。
int gcd(int m, int n)//m > n
{
while(n != 0)
{
int temp = m % n;
m = n;
n = temp;
}
return m;
}
int lcm(int a, int b)
{
return a / gcd(a,b) * b;
}
void fraction_reduction(int &ansX,int &ansY)//y is denominator,x is numerator
{
int g,kx = 0,ky = 0;//the k is mark whether x||y is positive
if(ansY == 0 || ansX == 0)
return;
if(ansX < 0)
{
kx = 1;
ansX -= ansX<<1;
}
if(ansY < 0)
{
ky = 1;
ansY -= ansY<<1;
}
if(ansX > ansY)
g = gcd(ansX,ansY);
else
g = gcd(ansY,ansX);
ansX /= g;
ansY /= g;
if(kx == 1)
ansX -= ansX<<1;
if(ky == 1)
ansY -= ansY<<1;
}
void fraction_add(int x1,int y1,int x2,int y2, int &ansX,int &ansY)//y is denominator,x is numerator
{
if(y1 > y2)
ansY = lcm(y1,y2);
else
ansY = lcm(y2,y1);
ansX = ansY/y1*x1 + ansY/y2*x2;
fraction_reduction(ansX,ansY);
}
void fraction_sub(int x1,int y1,int x2,int y2, int &ansX,int &ansY)
{
if(y1 > y2)
ansY = lcm(y1,y2);
else
ansY = lcm(y2,y1);
ansX = ansY/y1*x1 - ansY/y2*x2;
fraction_reduction(ansX,ansY);
}
void fraction_mul(int x1,int y1,int x2,int y2, int &ansX,int &ansY)
{//the precision is limited,so if you use it,you may use long long
ansX = x1*x2;
ansY = y1*y2;
fraction_reduction(ansX,ansY);
}
void fraction_division(int x1,int y1,int x2,int y2, int &ansX,int &ansY)
{
ansX = x1*y2;
ansY = x2*y1;
fraction_reduction(ansX,ansY);
}