Home > Blockchain >  Second function with same integers doesn't work
Second function with same integers doesn't work

Time:12-13

I have a task to create 2 functions to calculate GCD and LCM. But I noticed that my second function doesn't work not matter what calculation is there. What am I doing wrong ?

#include <iostream>
using namespace std;

int gcd(int number1,int number2);


int lcm(int number1,int number2);

int main()
{

    int number1;
    int number2;
    cout<<"enter number 1: ";
    cin>>number1;
    cout<<"enter number 2: ";
    cin>>number2;
    cout<<"The GCD of "<<number1<<" and "<<number2<<" is "<<gcd(number1,number2)<<endl;
    cout<<"The LCM of "<<number1<<" and "<<number2<<" is "<<lcm(number1,number2)<<endl;

    return 0;
}
    int gcd(int number1,int number2)
    {
        if (number2==0)
            return number1;
        return gcd(number2,number1 % number2);
    }

    int lcm(int number1,int number2)
    {
        return lcm(number2, number1 * number2)/gcd(number1,number2);
    }

Output:

enter number 1: 44
enter number 2: 121
The GCD of 44 and 121 is 11
The LCM of 44 and 121 is
Process returned -1073741571 (0xC00000FD)

CodePudding user response:

The problem lies within the lcm() function:

int lcm(int number1,int number2)
{
    return lcm(number2, number1 * number2)/gcd(number1,number2);
}

This function will be an infinite recursion because there's no base case. Eventually, you will run into, ironically, a stack overflow problem.

Looking at the nature of the function, I think what you meant is:

int lcm(int number1, int number2)
{
    return number1 * number2 / gcd(number1, number2);
}

CodePudding user response:

I believe this is what you wanted to do in your function?

#include <iostream>
using namespace std;

int gcd(int number1,int number2);

int lcm(int number1,int number2);

int main() 
{

int number1;
int number2;
cout<<"enter number 1: ";
cin>>number1;
cout<<"enter number 2: ";
cin>>number2;
cout<<"The GCD of "<<number1<<" and "<<number2<<" is "<<gcd(number1,number2)<<endl;
cout<<"The LCM of "<<number1<<" and "<<number2<<" is "<<lcm(number1,number2)<<endl;

return 0; }
int gcd(int number1,int number2)
{
    if (number2==0)
        return number1;
    
    return gcd(number2,number1 % number2);
    
}

int lcm(int number1,int number2)
{
    int lcmResult=number1 * number2/gcd(number1,number2);
    return lcmResult;
}

and the output i got is:

enter number 1: 44

enter number 2: 121

The GCD of 44 and 121 is 44

The LCM of 44 and 121 is 121
  • Related