Last active
February 7, 2017 05:34
-
-
Save fpdjsns/9f0c909cfa35b346e6498199835e5798 to your computer and use it in GitHub Desktop.
유리수의 사칙연산(Rational number Four fundamental rules of arithmetics)(add, subtraction, multiplication, division
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
using namespace std; | |
typedef struct _Rational { | |
int bunZa, bunMo; | |
} Rational; | |
//Greatest common divisior(최대공약수) | |
int GCD(int a, int b) | |
{ | |
if (b == 0) return a; | |
else return GCD(b, a%b); | |
} | |
//Least common multiple(최소공배수) | |
int LCM(int a, int b) | |
{ | |
return a*b / GCD(a, b); | |
} | |
//Reduction(약분) | |
Rational reduction(Rational a) | |
{ | |
int gcd = GCD(a.bunZa, a.bunMo); | |
a.bunZa /= gcd; | |
a.bunMo /= gcd; | |
return a; | |
} | |
//Add | |
Rational RationalAdd(Rational a, Rational b) | |
{ | |
Rational result; | |
result.bunMo = LCM(a.bunMo, b.bunMo); | |
result.bunZa = a.bunZa*(result.bunMo / a.bunMo); | |
result.bunZa += b.bunZa*(result.bunMo / b.bunMo); | |
return reduction(result); | |
} | |
//Subtraction | |
Rational RationalSub(Rational a, Rational b) { | |
Rational result; | |
result.bunMo = LCM(a.bunMo, b.bunMo); | |
result.bunZa = a.bunZa*(result.bunMo / a.bunMo); | |
result.bunZa -= b.bunZa*(result.bunMo / b.bunMo); | |
return reduction(result); | |
} | |
//Multiplication | |
Rational RationalMul(Rational a, Rational b) { | |
Rational temp; | |
a = reduction(a); | |
b = reduction(b); | |
temp.bunMo = b.bunMo; | |
temp.bunZa = a.bunZa; | |
temp = reduction(temp); | |
b.bunMo = temp.bunMo; | |
a.bunZa = temp.bunZa; | |
temp.bunMo = a.bunMo; | |
temp.bunZa = b.bunZa; | |
temp = reduction(temp); | |
a.bunMo = temp.bunMo; | |
b.bunZa = temp.bunZa; | |
temp.bunMo = a.bunMo*b.bunMo; | |
temp.bunZa = a.bunZa*b.bunZa; | |
return temp; | |
} | |
//Division | |
Rational RationalDiv(Rational a, Rational b) { | |
int temp = b.bunZa; | |
b.bunZa = b.bunMo; | |
b.bunMo = temp; | |
return RationalMul(a, b); | |
} | |
int main() | |
{ | |
Rational a = { 2, 5 }; // 2/5 | |
Rational b = { 2, 10 }; // 2/10 | |
Rational c, d, e, f; | |
c = RationalAdd(a, b); | |
printf(" e = %d/%d\n", c.bunZa, c.bunMo); | |
d = RationalSub(a, b); | |
printf(" d = %d/%d\n", d.bunZa, d.bunMo); | |
e = RationalMul(a, b); | |
printf(" e = %d/%d\n", e.bunZa, e.bunMo); | |
f = RationalDiv(a, b); | |
printf(" f = %d/%d\n", f.bunZa, f.bunMo); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment