Help with Greatest Common Divisor

I'm supposed make a program that finds the greatest common divisor between two numbers. I've been trying to convert the euclidean algorithm into c++ and place it in a while loop but I feel like GCD is beyond me. I've got 3 pages of a notebook filled up with different ways of looking at the euclidean algorithm and I just can't comprehend what's going on. I can't understand how a mod operator would allow you to find a Greatest Common Divisor. Honestly, I'm just wanting someone to make this program for me but in a dumbed down way that I can understand.

Here's how it's supposed to work: User enters a pair of numbers separated by a space, then the program outputs the GCD. I'd prefer a while loop. Any takers?


 
% gives you the remainder of division. A simple approach would be to loop through all numbers between 2 and the lowest of your two numbers and keep track of the largest number that has no remainder of division for both numbers.
Let's say you want to find the greatest common divisor for 8 and 12.
 
for (int i = 12; i >= 2; i--)


Start looping at the larger number (12), checking the remainder when the numbers are divided by i (8 % i) and (12 % i)
If the modulo of both the numbers are 0, we have found the greatest common divisor.

i = 12
8 % 12 = 8
12 % 12 = 0

i = 11
8 % 11 = 8
12 % 11 = 1

i = 10
8 % 10 = 8
12 % 10 = 2

...

i = 4
8 % 4 = 0
12 % 10 = 0

Both of the remainders are 0, so we found the greatest common divisor (4).

And if you can't find the greatest common divisor, by default it's 1.
Last edited on
I finally got the program working!
But how do I keep it running so that the user can keep typing in a new set of numbers after getting an output? I want it to revert back to where the user types in an input. And I want the program to be able to stop if they input 111.
https://en.wikipedia.org/wiki/Euclidean_algorithm#Implementations

1
2
3
4
5
6
int gcd( int a, int b ) // recursive version
{
    if( b == 0 ) return a<0 ? -a : a ;
    
    else return gcd( b, a%b ) ;
}
1
2
3
4
5
6
7
8
int number_to_test;
while((std::cout << "Enter a number to test, or 111 to exit: ")
   && (std::cin >> number_to_test)
   && (number_to_test != 111)
)
{
    //your code here
}
Last edited on
Do you know how I can differentiate between 00 and 0 when the user enters this number? I want 00 to terminate the program, but entering a set of numbers like 0 7 to still work. So far, 0 7 terminates the program just like 00 does.
Take input as a string and check for "00" before converting to a number.

Possibly helpful:
http://www.LB-Stuff.com/user-input
Topic archived. No new replies allowed.