1

I was lookin for a code to implement the LCM of two numbers using recursion. Here is the code i found:

#include<stdio.h>
int lcm(int a, int b)
{
    static int common = 1;
 
    if (common % a == 0 && common % b == 0)
    {
        return common;
    }
    common++;
    lcm(a, b);  //call the function lcm recursively.
}
void main()
{
    int a=5;
    int b=6;
    int c= lcm(a,b);
    printf("\n%d",c);
}

I understand everything but the last line in the lcm(int a, intb) function

lcm(a,b);

According to me, for lets say input values 5,2 there will be 10 recursive calls made in the stack after which our base condition is reached. Now for the statement:

return common;

where does it return the value to? we are not really saving it anywhere in the 9th recursive call in the stack. How is it getting passed down the hierarchy and making its way to void main. If the recursive call was written as-

return lcm(a,b);

I understand how this works- we return the 10th recursive function call to 9th and then to 8th and so on... until it makes it way to void main when we return from the first time function was called.

  • 1
    Don't you ignore a compilation error message ? –  Dec 09 '22 at 18:25
  • 1
    It looks like the code causes undefined behavior because it does not return a value in all cases. It may appear to work accidentally but that isn't guaranteed. It could just as easily fail in any number of ways. – Retired Ninja Dec 09 '22 at 18:26
  • I think you are trying to exhaustively check all numbers; there are [other methods that are much better](https://en.wikipedia.org/wiki/Least_common_multiple#Calculation). – Neil Dec 09 '22 at 18:35

0 Answers0