|
1 | 1 | """
|
2 | 2 | Gcd of N Numbers
|
3 | 3 | Reference: https://en.wikipedia.org/wiki/Greatest_common_divisor
|
4 |
| -Reference for tail recursion: https://www.geeksforgeeks.org/tail-recursion/ |
5 | 4 | """
|
6 | 5 |
|
7 | 6 | from collections import Counter
|
@@ -106,59 +105,5 @@ def get_greatest_common_divisor(*numbers: int) -> int:
|
106 | 105 | return mult
|
107 | 106 |
|
108 | 107 |
|
109 |
| -def gcd_tail_recursive(a: int, b: int) -> int: |
110 |
| - """ |
111 |
| - Calculate the Greatest Common Divisor (GCD) using a tail-recursive approach. |
112 |
| -
|
113 |
| - This function uses the tail-recursive form of |
114 |
| - the Euclidean algorithm to calculate |
115 |
| - the GCD of two integers `a` and `b`. The GCD |
116 |
| - is the largest integer that divides both |
117 |
| - `a` and `b` without leaving a remainder. |
118 |
| -
|
119 |
| - Tail recursion is a form of recursion where the |
120 |
| - recursive call is the last operation |
121 |
| - in the function. In languages that |
122 |
| - support tail call optimization, this allows the |
123 |
| - function to be optimized by reusing the current |
124 |
| - function's stack frame for the |
125 |
| - next call. Python, however, does not support tail |
126 |
| - call optimization, but using this |
127 |
| - style can still help structure the |
128 |
| - recursion for better clarity. |
129 |
| -
|
130 |
| - Args: |
131 |
| - a (int): The first integer. |
132 |
| - b (int): The second integer. |
133 |
| -
|
134 |
| - Returns: |
135 |
| - int: The greatest common divisor of `a` and `b`. |
136 |
| -
|
137 |
| - Raises: |
138 |
| - ValueError: If both `a` and `b` are zero, as the GCD is not defined for this case. |
139 |
| -
|
140 |
| - Example: |
141 |
| - >>> gcd_tail_recursive(24, 40) |
142 |
| - 8 |
143 |
| - >>> gcd_tail_recursive(11, 37) |
144 |
| - 1 |
145 |
| - >>> gcd_tail_recursive(0, 5) |
146 |
| - 5 |
147 |
| - >>> gcd_tail_recursive(5, 0) |
148 |
| - 5 |
149 |
| - >>> gcd_tail_recursive(0, 0) |
150 |
| - ValueError: GCD is not defined for both a and b being zero. |
151 |
| -
|
152 |
| - Notes: |
153 |
| - - gcd(a, 0) = abs(a) |
154 |
| - - gcd(0, b) = abs(b) |
155 |
| - - gcd(0, 0) is undefined. |
156 |
| - """ |
157 |
| - if b == 0: |
158 |
| - return abs(a) |
159 |
| - return gcd_tail_recursive(b, a % b) |
160 |
| - |
161 |
| - |
162 | 108 | if __name__ == "__main__":
|
163 | 109 | print(get_greatest_common_divisor(18, 45)) # 9
|
164 |
| - print(gcd_tail_recursive(23, 37)) # 1 |
0 commit comments