C++ program - LCM&GCF problems

2007-01-09 3:52 pm
Write a program to add two fractions and print the answer as a proper fraction in reduced form. Write, test and debug the following program before you write the fraction program.
a) write and test functions GCF(Greatest Common Factor) and LCM (Lowest Common Multiple).
b) Use the GCF and LCM fuctions to write the addition of fractions program.

回答 (1)

2007-01-09 9:33 pm
✔ 最佳答案
a)
To write a program calculating LCM, the simplest and the best way is to use Eucildean Algorithm:
http://hk.knowledge.yahoo.com/question/?qid=7006122601457

To calculate GCF, notice that for two integers a and b, |a*b| = LCM(a,b) * GCF(a,b)
This is easy to check using the method of finding LCM and GCF by factorization

b)
To add two fractions, first you must find the "common multiple" for the denominators
Then add two numinators, then simplify it:

Fraction Add(Fraction &a, Faction &b) {
int gcf = GCF(a.denominator, b.denominator)
int new_numinator = a. numinator*(gcf/a.denominator) + b.numinator*(gcf/b.denominator)
int lcm = LCM(gcf, new_numinator);
gcf = gcf / lcm;
new_numinator = new_numinator/lcm;
return new Fraction(new_numinator, gcf);
}


收錄日期: 2021-04-23 16:33:59
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20070109000051KK00419

檢視 Wayback Machine 備份