By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,009 Members | 1,487 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,009 IT Pros & Developers. It's quick & easy.

Euclids Algorithm code problem

P: n/a
Hi,
I am having trouble with my code. My program compiles and runs correctly if the value for X is less than Y. If the value of X is greater than Y it gives me a GCD of one because it is still executing the statements for the If statement. I know it has to do with the scope of my if statement. Does anyone have any suggestions?

Expand|Select|Wrap|Line Numbers
  1. #include <iostream> 
  2.  
  3. using namespace std ;
  4.  
  5. int main() 
  6.  
  7.     int x ;
  8.     int y ;
  9.     int temp ;
  10.     int remainder ;
  11.  
  12.     // read in the two integers
  13.  
  14.     cout << endl ;
  15.     cout << "Enter the first number (integer) : " ; 
  16.     cin >> x ;
  17.     cout << "Enter the second number (integer) : " ; 
  18.     cin >> y ;
  19.  
  20.     //echo inputs
  21.  
  22.     cout << "Input numbers are: " << x << " , " << y << endl ;
  23.  
  24.  { // exchange values of x and y 
  25.  
  26.  
  27.      if (x < y) 
  28.  
  29.      temp = x ;
  30.      x = y ;
  31.      y = temp ;  
  32.  
  33.  
  34.  }
  35.  
  36.     /* At this point we will always have x >= y */
  37.  
  38.  
  39.  
  40.  
  41.     while (x % y != 0)
  42.         {         
  43.          x = y ;
  44.          y = remainder ;
  45.          remainder = (x % y) ;
  46.         }
  47.  
  48.     // display the result
  49.     cout << endl ;
  50.     cout << "The GCD is: " << y << endl ;
  51.     system("PAUSE");
  52.     return (0); // terminate with success
  53. }
  54.  
Oct 30 '10 #1
Share this Question
Share on Google+
1 Reply


Banfa
Expert Mod 5K+
P: 8,916
Put braces { } round the code that should be part of the if statement block.
Oct 31 '10 #2

Post your reply

Sign in to post your reply or Sign up for a free account.