Skip to content

Commit 6f59b36

Browse files
committed
feat(day 97): compute greatest common divisor using Euclidean algorithm
1 parent 402fffd commit 6f59b36

1 file changed

Lines changed: 51 additions & 0 deletions

File tree

FreeCodeCamp/CodingQ/GCD.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
"""
2+
3+
GCD
4+
Given two positive integers, return their greatest common divisor (GCD).
5+
6+
The GCD of two integers is the largest number that divides evenly into both numbers without leaving a remainder.
7+
For example, the divisors of 4 are 1, 2, and 4. The divisors of 6 are 1, 2, 3, and 6. So given 4 and 6, return 2, the largest number that appears in both sets of divisors.
8+
"""
9+
10+
import unittest
11+
12+
class GCDTest(unittest.TestCase):
13+
14+
def test1(self):
15+
self.assertEqual(gcd(4, 6),2)
16+
17+
def test2(self):
18+
self.assertEqual(gcd(20, 15),5)
19+
20+
def test3(self):
21+
self.assertEqual(gcd(13, 17), 1)
22+
23+
def test4(self):
24+
self.assertEqual(gcd(654, 456), 6)
25+
26+
def test5(self):
27+
self.assertEqual(gcd(3456, 4320), 864)
28+
29+
30+
31+
32+
def gcd(x, y):
33+
min_div = 0
34+
for i in range(1, y):
35+
if x%i == 0 and y%i == 0:
36+
min_div = i
37+
38+
return min_div
39+
40+
def gcd(x, y):
41+
42+
while (y!=0):
43+
x , y = y , x%y
44+
45+
return x
46+
47+
48+
49+
if __name__ == "__main__":
50+
print(gcd(20, 15))
51+
unittest.main()

0 commit comments

Comments
 (0)