Problem with Modulus Operator

Hi there, have been working on final question to course work and have come across some problems with getting my modulus operator to work.
I am trying to find the GCD of two integers given and have gotten up to this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
  #include <iostream>
#include <cmath>
using namespace std;
int main()
{
    double num1, num2, remainder, d, a, b;
    
    
    cout<<"This program determines the Greatest Common Denominator"<<endl;
    cout<<"in all numbers."<<endl<<endl;
    cout<<"Please input the two numbers you would like to calculate"<<endl;
    cout<<"the GCD for."<<endl<<endl;
    cout<<"num1:";
    cin>>num1;
    cout<<"num2:";
    cin>>num2;
    
    remainder = a%d;
    
    while (remainder > 0){
          a=b;
          b=remainder;
          remainder=(a%b);}
          
    cout<<b;
    
    system("PAUSE");
    return EXIT_SUCCESS;
}



Any help on my misuse of the modulus operator would be greatly appreciated.

Cheers,
Cameron
A really good habit to start doing is to initialize ( or give a value to) every variable you create. If you don't, it will have a value of -909382093842390, or something like that. Just set them to zero. a = 0, b = 0, //....and so on...

So when you are doing a % b , you're really working with those large negative numbers.

And you cin into num1 and num2 , but you don't use them anywhere.

d is not used anywhere.

I think you have the idea correct. You just need to use the right variables and stuff.

And you should also consider the possibility when remainder = a % b....is equal to zero at the start, and the while loop is never executed. What should "b" be then?
Last edited on
I fear you use too many variables (a, b, d, remainder) instead of only two (a, b) which lead you to some bewilderment and mess.

http://codeabbey.com/index/wiki/gcd-and-lcm

Here I described this algorithm - and at the bottom you can also find a link to task on GCD with the automated answer checker.

Shortly speaking you need at each iteration see which number is bigger and substitute it by (bigger % smaller). No other variables are needed.
Thank you for your help Bingo!
Topic archived. No new replies allowed.