![]() |
|
[C] Algorithm Series - 2 | GCD and LCM - Printable Version +- Hack Forums (https://hackforums.net) +-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444) +--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151) +---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118) +---- Thread: [C] Algorithm Series - 2 | GCD and LCM (/showthread.php?tid=4683617) |
Algorithm Series - 2 | GCD and LCM - Deadbyte - Feb 13, 2015 Algorithm Series - 2 | GCD and LCM Greatest common divisor The greatest common divisor (gcd) or Highest common factor ( HCF ) of two integers is the greatest (largest) number that divides both of the integers evenly. Euclid came up with the idea of GCDs. Algorithm The GCD of any two positive integers can be defined as a recursive function: gcd(u,v) = { gcd(u,v mod v) if v > 0 gcd(u,v) = { u, if v = 0 Examples The GCD of 20 and 12 is 4, since 4 times 5 equals 20 and 4 times 3 equals 12. You can notice 3 and 5 have no common factor, hence their GCD is 1. The GCD of 81 and 21 is 3. Code in C++ PHP Code Least common multiple The least common multiple of two integers is the smallest positive integer between all the multiples of both. It is usually denoted by LCM(a, b). Likewise, the LCM of more than two integers is the smallest positive integer that is divisible by each of them. The LCM is known in elementary arithmetic as the "least common denominator" (LCD) that must be calculated before fractions can be added, subtracted or compared. Algorithm GCD(a,b) * LCM(a,b) = |a*b| This formula is often used to compute the LCD, once known the GCD of a and b. Code in C++ PHP Code Notice: The algorithms that I am introducing in the series are simplistic some inefficient and slow but the series are for educational purpose for beginners in competitive programming. |