I'm trying to write the Euclidean Algorithm in Python. It's to find the GCD of two really large numbers. The formula is a = bq + r where a and b are your two numbers, q is the number of times b divides a evenly, and r is the remainder. I can write the code to find that, however if it the original numbers don't produce a remainder (r) of zero then the algorithm goes to step 2 => b = rx + y. (same as the first step but simply subbing b for a, and r for b) the two steps repeat until r divides both a and b evenly. This is my code, I haven't yet figured out how to do the subbing of values and create a loop until the GCD is found.
Chris Martin 29.6k8 gold badges74 silver badges131 bronze badges asked Feb 6, 2014 at 16:32 2
or use
answered Feb 6, 2014 at 16:43 zhangxaochenzhangxaochen 31.2k15 gold badges71 silver badges105 bronze badges Try This
answered Oct 23, 2018 at 13:50 I know this is old post but here it is:
Taken from Algorithms 4th edition. Note: if your numbers are REALLY REALLY large then try to increase the recursion limit by:
but be very very careful with it. I was able to fill my 12GB RAM and cause a freeze quite easily. answered May 15, 2021 at 22:27 I think that's the shortest solution:
answered Sep 29, 2021 at 18:44 I think there's one missing important condition for Euclidean Algorithm to work, which is a >= b > 0. So may I suggest this code I just made (quite long cuz I haven't viewed prev answers before building it haha.
answered Jan 13 at 13:10 I recently came across a question like this in my math class. The code I wrote was:
answered Aug 20 at 2:59 Not the answer you're looking for? Browse other questions tagged python or ask your own question.View Discussion Improve Article Save Article View Discussion Improve Article Save Article Python3
Output: GCD(10, 15) = 5 GCD(35, 10) = 5 GCD(31, 2) = 1 Time Complexity: O(Log min(a, b)) Auxiliary Space: O(Log min(a, b)), due to recursion stack. Please refer complete article on Basic and Extended Euclidean algorithms for more details! |