Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit f3ed52b

Browse filesBrowse files
dvdvgtabranhe
authored andcommitted
Added recursive function to determine the greatest common divisor of two integers
1 parent f63cd01 commit f3ed52b
Copy full SHA for f3ed52b

File tree

Expand file treeCollapse file tree

1 file changed

+26
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+26
-0
lines changed
+26Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
"""
2+
In mathematics, the greatest common divisor (gcd) of two or more integers,
3+
which are not all zero, is the largest positive integer that divides each of the integers.
4+
For example, the gcd of 8 and 12 is 4.
5+
» https://en.wikipedia.org/wiki/Greatest_common_divisor
6+
7+
Due to limited recursion depth this algorithm is not suited for calculating the GCD of big integers.
8+
"""
9+
10+
def recGCD(x, y, div = 0):
11+
# Detemine which integer is greater and set the divisor accordingly
12+
if div == 0:
13+
if x > y:
14+
div = x
15+
else:
16+
div = y
17+
# If both integers can be divided without a remainder the gcd has been found
18+
if x % div == 0 and y % div == 0:
19+
return div
20+
# Decrease divisor by one and try again
21+
else:
22+
return recGCD(x, y, div-1)
23+
24+
x = int(input("x = "))
25+
y = int(input("y = "))
26+
print(f"gcd({x}, {y}) = {recGCD(x,y)}")

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.