Deitel C++ How To Program 9th Edition Chapter 6 Exercise 6.37

15 Jul 2024 - Syed Muhammad Shahrukh Hussain

Write a program to find LCM (Least Common Multiple) of two numbers using recursive function.

Terminal

Input number 1: 2
Input number 2: 3
LCM:
divisor: 1 num1: 2 num2: 3
divisor: 2 num1: 2 num2: 3
divisor: 3 num1: 1 num2: 3
6

Solution

#include <iostream>

using namespace std;

int lcm(int, int, int);

int main() {
  int divisor = 1; // initializing it by 1 as 0 divisor is an error.
  int number1;
  int number2;

  cout << "Input number 1: ";
  cin >> number1;
  cout << "Input number 2: ";
  cin >> number2;
  cout << "LCM: " << endl << lcm(number1, number2, divisor) << endl;
  return 0;
}

int lcm(int num1, int num2, int divisor) {
  int total = 1;

  if (num1 == 1 && num2 == 1) {
    return 1;
  }
  cout << "divisor: " << divisor << " num1: " << num1 << " num2: " << num2 << endl;
  if (divisor == 1) {
    return total * lcm(num1, num2, divisor + 1);
  }
  if (0 == num1 % divisor) {
    total = divisor;
    num1 /= divisor;
  }
  if (0 == num2 % divisor) {
    total = divisor;
    num2 /= divisor;
  } else {
    divisor++;
  }
  return total * lcm(num1, num2, divisor);
}

Sources