How do I get my GCD to calculate right when I run my program, I put in  36 & 48 and I get the number 0

deteminewoman
deteminewoman used Ask the Experts™
on
#include "stdafx.h"
#include <iostream>
using namespace std ;

int _tmain(int argc, _TCHAR* argv[])

{
//Declare x, y, temp, remainder as Integer.
int x;
int y; ;
int temp;
int remainder  = 1; // Compute GCD
   
    //read in the two integers
     
    cout << endl ;
    cout << "Enter the first number (integer) : " ;
    cin >> x ;
    cout << "Enter the second number (integer) : " ;
    cin >> y ;

    //echo inputs

    cout << "Input numbers are: " << x << " , " << y << endl;

    {// exchange values of x and y
   
    if(x < y)
    {
        int temp = x;
        x = y;
        y = temp;
    }
    else if(x < 1)
    {
        x = x - 1 ;
    }
    else
    {
        x = x + 1 ;
    }
}

    /* At this point we will always have x >= y */

    //Initialize remainder.
 
    while(remainder!=0)
{
    remainder = x % y;
    x = y;
    y = remainder;
}

    // display the result
    cout << endl ;
    cout << "The GCD is: " << y << endl ;

    system("PAUSE");
    return (0);
}
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
>>>>         int temp = x;


here you define an *additional* local variable temp which is only valid within the { } block where it was defined.

remove the int before temp and it will work.
Commented:
Your loop ends when remainder is 0, but just befor exit loop you assign remainder to y, so at the end, y is always 0.
It should be:
int last_remainder;
 
while(remainder!=0)
{
   last_remainder  = remainder;
   remainder = x % y;
   x = y;
   y = remainder;
}
 
// display the result
cout << endl ;
cout << "The GCD is: " << last_remainder << endl ;

Open in new window

alb66 is right.

the 'int temp' is unnecessary but is not the reason for the y being 0.

Commented:
Comment #24877134 is the right answer.
I tested it and it works.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial