gcd

This is a discussion on gcd within the C++ Programming forums, part of the General Programming Boards category; Why is this code returning the wrong gcd? Code: #include <iostream> using namespace std; int gcd(int a,int b); int main() ...

  1. #1
    Registered User Kayoss's Avatar
    Join Date
    Sep 2005
    Location
    California
    Posts
    53

    gcd

    Why is this code returning the wrong gcd?

    Code:
    #include <iostream>
    
    using namespace std;
    
    int gcd(int a,int b); 
    
    int main() 
    {
    
    	double a = 0;
    	double b = 0; 
    
        cout << "Enter two integers and I will report their gcd: " << endl;
        cin >> a,b;
        cout << gcd(a,b) << endl;
    
        return 0;
       
    } 
    
    
    int gcd(int a, int b)
    
    {
    
    while ( b !=0 ) 
    
    {
    
    int t = b;
    b = a % b;
    a = t;
    
    }
    
    return a;
    
    }
    THE redheaded stepchild.

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    Code:
    cin >> a,b;
    You cannot use commas like that. Read in a and b separately. Then try again and see if it works.

  3. #3
    Hardware Engineer
    Join Date
    Sep 2001
    Posts
    1,398
    int t is being declared multiple times... each time through the loop. Define it once outside the loop, then assign a value to it each time through the loop.

    Code:
    int gcd(int a, int b)
    {
        int t;
        
        while ( b !=0 ) 
         {
               t = b;
               b = a % b;
               a = t; 
         }
    
         return a;
         }

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    >> int t is being declared multiple times

    That doesn't matter in this case because it is being assigned to b immediately either way.

  5. #5
    Registered User Kayoss's Avatar
    Join Date
    Sep 2005
    Location
    California
    Posts
    53
    Ah, I read in the variables separately and it worked. Thanks much!
    THE redheaded stepchild.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Gcd on three numbers
    By Ideswa in forum C Programming
    Replies: 7
    Last Post: 03-19-2009, 02:57 PM
  2. computing the GCD non-recursively
    By rrreeefff in forum C Programming
    Replies: 2
    Last Post: 10-05-2008, 11:57 PM
  3. NEED help with returning the GCD
    By SuPaNooB in forum C Programming
    Replies: 3
    Last Post: 11-04-2007, 12:16 PM
  4. GCD as fast as possible!
    By fischerandom in forum C Programming
    Replies: 21
    Last Post: 11-22-2005, 11:20 AM
  5. GCD For all of You!
    By Argentina in forum C Programming
    Replies: 0
    Last Post: 02-14-2002, 04:38 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21