Calculate the lcm between two natural numbers using recursion.

Example: lcm(1220,516) ?

Multiple of 516 are: 516 1032 1548 2064 ... 157380 ...

Multiple of 1220 are: 1220 2440 ... 157380 ...

Method 1:

  • Check whether the maximum number clearly divides both number or not. If it does, then end the process and return the maximum as LCM.
  • If maximum doesn't divides both given numbers then increment it by the max values among both given numbers.

Difficulty level
This exercise is mostly suitable for students
#include <stdio.h>
#include <conio.h>

// a needs to be always less than b
int lcm(int a, int b, int val)
{
	if ((val % a == 0) && (val % b == 0))
		return val;
	return lcm(a, b, val+b);
}

void main()
{
	int a, b, answer;

	printf("Enter 2 integers: ");
	scanf("%d %d", &a, &b);


	if (a > b)
		answer =lcm(b, a, a);
	else
		answer = lcm(a, b, b);

	printf("lcm(%d,%d)=%d", a, b, answer);

	getch();
}

 

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Sorting using merge-sort algorithm