Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Second function with same integers doesn't work

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading