12,699,054 members (24,819 online)
Alternative Tip/Trick
alternative version

3.9K views
1 bookmarked
Posted

# Fast Greatest Common Divisor (GCD) Algorithm

, 11 Feb 2011 CPOL
 Rate this:
Can we simplify it by: (This essentially passes only two numbers). public int GCD(int value1, int value2){ int max = 0; bool gcdFound = false; int counter = 1; //Make sure both numbers are atleast 2 or above if (( value1 <= 1 ) || (value2 <= 1)) return...
Can we simplify it by: (This essentially passes only two numbers).

```public int GCD(int value1, int value2)
{

int max = 0;
bool gcdFound = false;
int counter = 1;

//Make sure both numbers are atleast 2 or above
if (( value1 <= 1 ) || (value2 <= 1))
return (value1 < value2 ? value1 : value2);

//If one of the two numbers is the exact divisor of then other or are equal to each other then we return that number here.
gcdFound = (((value1 % value2 ) == 0 ) || ((value2 % value1 ) == 0 ));
if (gcdFound)
{
return (value1 > value2 ? value2 : value1);
}

//Find the larger of the two numbers, the GCD can not be more than half of the smaller number.
max =  value1 > value2 ? (value2 / 2) : (value1 / 2);
counter = max + 1;

while ((!gcdFound) && (counter > 1))
{
counter--;
gcdFound = ((value1 % counter) == 0) && ((value2 % counter) == 0);
}

return counter;
}```

## About the Author

 United States
No Biography provided

## You may also be interested in...

 Pro Pro

## Comments and Discussions

 First Prev Next
 As I've already mentioned: DO NOT USE THIS ALTERNATE ALGORIT... DrABELL22-Feb-11 17:00 DrABELL 22-Feb-11 17:00
 Reason for my vote of 5 It works. Kamran Behzad22-Feb-11 15:08 Kamran Behzad 22-Feb-11 15:08
 Last Visit: 31-Dec-99 19:00     Last Update: 22-Jan-17 4:49 Refresh 1

General    News    Suggestion    Question    Bug    Answer    Joke    Praise    Rant    Admin

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.