Greatest common divisor: what changed
Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.
Title: Greatest common divisor
| Old | New | Line | |
|---|---|---|---|
| 1 | + | The greatest common divisor of two integers is the largest integer that divides them both. If numbers are 121 and 143 then greatest common divisor is 11. | |
| 2 | + | ||
| 3 | + | There are many methods to calculate this. For example, the division-based Euclidean algorithm version may be programmed: | |
| 4 | + | ||
| 5 | + | ## `function greatestCommonDivisor` | |
| 6 | + | ||
| 7 | + | ``` pascal | |
| 8 | + | function greatestCommonDivisor(a, b: Int64): Int64; | |
| 9 | + | var | |
| 10 | + | temp: Int64; | |
| 11 | + | begin | |
| 12 | + | while b <> 0 do | |
| 13 | + | begin | |
| 14 | + | temp := b; | |
| 15 | + | b := a mod b; | |
| 16 | + | a := temp | |
| 17 | + | end; | |
| 18 | + | result := a; | |
| 19 | + | end; | |
| 20 | + | ||
| 21 | + | function greatestCommonDivisor_euclidsSubtractionMethod(a, b: Int64): Int64; | |
| 22 | + | begin | |
| 23 | + | // only works with positive integers | |
| 24 | + | if (a < 0) then a := -a; | |
| 25 | + | if (b < 0) then b := -b; | |
| 26 | + | // don't enter loop, since subtracting zero won't break condition | |
| 27 | + | if (a = 0) then exit(b); | |
| 28 | + | if (b = 0) then exit(a); | |
| 29 | + | while not (a = b) do | |
| 30 | + | begin | |
| 31 | + | if (a > b) then | |
| 32 | + | a := a - b | |
| 33 | + | else | |
| 34 | + | b := b - a; | |
| 35 | + | end; | |
| 36 | + | result := a; | |
| 37 | + | end; | |
| 38 | + | ``` | |
| 39 | + | ||
| 40 | + | ## see also | |
| 41 | + | ||
| 42 | + | - [[Least common multiple|least common multiple]] | |
| 43 | + | - [[Mod|mod operator]] | |
| 44 | + | - `mpz_gcd` in [[gmp|GMP]] (GNU multiple precision) | |
| 45 | + | ||
| 46 | + | ## external references | |
| 47 | + | ||
| 48 | + | - [Recursive example](https://rosettacode.org/wiki/Greatest_common_divisor#Pascal_.2F_Delphi_.2F_Free_Pascal) | |
| 49 | + | ||
| 50 | + | --- | |
| 51 | + | *From the Free Pascal wiki, page "Greatest common divisor", as it stood on 2023-12-13 after a change by Rvr, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).* | |
| 52 | + | Category: Mathematics |
