Last active
September 2, 2020 02:13
-
-
Save sergiosvieira/47ed3d5463fd9eb257032e65425525ca to your computer and use it in GitHub Desktop.
Binary GCD
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| unsigned int gcd(unsigned int u, unsigned int v) | |
| { | |
| // simple cases (termination) | |
| if (u == v) | |
| return u; | |
| if (u == 0) | |
| return v; | |
| if (v == 0) | |
| return u; | |
| // look for factors of 2 | |
| if (~u & 1) // u is even | |
| if (v & 1) // v is odd | |
| return gcd(u >> 1, v); | |
| else // both u and v are even | |
| return gcd(u >> 1, v >> 1) << 1; | |
| if (~v & 1) // u is odd, v is even | |
| return gcd(u, v >> 1); | |
| // reduce larger argument | |
| if (u > v) | |
| return gcd(u - v, v); | |
| return gcd(v - u, u); | |
| } | |
| int findGCD(int arr[], int n) | |
| { | |
| int result = arr[0]; | |
| for (int i = 1; i < n; i++) | |
| { | |
| result = gcd(arr[i], result); | |
| if(result == 1) | |
| { | |
| return 1; | |
| } | |
| } | |
| return result; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment