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 2:

  • calculate thr common factors of each number, then pick the GCD 
    GCD(516,1220) = 4
  • LCM is equal to the multiplication ob both number divided by the GCD
    LCM(516,1220) = ( 516 × 1220) / 4
    LCM(516,1220) = 629520 / 4
    LCM(516,1220) = 157380

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

int gcd(int a, int b)
{
	if (b == 0)
		return a;
	return gcd(b, a%b);
}

int lcm(int a, int b)
{
	return a*b/gcd(a,b);
}

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

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

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

	getch();
}

 

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Hopscotch hashing