Question

Ok, so heres my simple program for calculating Greatest common divisor. It is returning a garbage value everytime the same as 46332964. Ive thought over my head for an hour but cant seem to understand the problem. After research, i also included the prototype but still no luck. It works until it returns. Please copy the code and run it and please help me.

#include <iostream>
using namespace std;

int calculate_gcd(int aa, int bb, int rem, int g);

int main()
{
    int a, b;
    int rem = -1;
    int gcd=0;

    cout << "Number 1: "; //taking inputs
    cin >> a;
    cout << "Number 2: ";
    cin >> b;

    if (a < b) //swapping if number greater than the number according to the code
    {
       a = a + b;
       b = a - b;
       a = a - b;
    }

    gcd = calculate_gcd(a, b, rem, gcd);

    if (a <= 0 || b <= 0)
    {
       rem = 0;
       cout <<"GCD doesnot exists\n";
    } //just in case of zeros
    else
        cout << "\nthe GCD of "<<a <<" and "<<b <<" is "<<gcd <<"\n\n"; //the main answer

    system("pause");
    return 0;
}

int calculate_gcd(int aa, int bb, int rem, int g)
{
    if (rem != 0)
    {
       if (aa%bb == 0)
        {
           rem = 0;
           g = bb;
           printf("**GCD is %d\n", g);
        }
        else {
             rem = aa % bb;
             aa = bb;
             bb = rem;
        }
        calculate_gcd(aa, bb, rem, g);
    }
    else {
         printf("**here also GCD is correct as %d \n", g);
         return g; //returning 
         }
}
Was it helpful?

Solution 2

You're missing a return. You should use return calculate_gcd(aa, bb, rem, g); instead of just recursing.

You can catch this with clang using -Wreturn-type. Other compilers probably also have a warning for this.

OTHER TIPS

The function head

int calculate_gcd(int aa, int bb, int rem, int g)

specifies that g is passed by value.

That means that in a call, the specified value is copied to this function invocation’s local g. Changes to that local g have no effect on the calling site.

Instead you should return the function result, and then you don’t need the g argument:

int calculate_gcd(int aa, int bb, int rem)

Closer analysis will show you that you do not really need the rem argument either, so:

int calculate_gcd(int aa, int bb)

In passing, as a beginner you will benefit greatly from using C++ iostreams, like cout, instead of low level C i/o functions like printf. That’s because printf and family do not perform any type checking, so it’s very easy to get wrong.

Also, although this may sound like just balderdash, you will benefit much by lining things up properly vertically, i.e. by using 100% consistent indentation. Happily there are free tools that help with this. If your favorite IDE or editor doesn’t support automatic source code formatting, then check out the free AStyle program.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top