Find three integers less than or equal to N such that their LCM is maximum - C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that is based on the concepts of LCM. As the title says, we have to find three numbers that are less than or equal to the given number whose LCM is maximum.

Let's see an example.

Before diving into the problem let's see what LCM is and write program for it.

LCM is the least common multiple of a number. It is also known as Least common divisor. For two positive number a and b, the LCM is the smallest integer that is evenly divisible by both a and b.

If the given integers don't have common factor, then the LCM is the product of the given numbers.

Example

Let's write the program to find LCM of any two positive numbers given.

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int a = 4, b = 5;
   int maximum = max(a, b);
   while (true) {
      if (maximum % a == 0 && maximum % b == 0) {
         cout << "LCM: " << maximum << endl;
         break;
      }
      maximum++;
   }
}

Output

If you run the above program, you will get the following output.

20

We have seen what LCM is and program to find the LCM of two positive numbers.

Let's see the steps to solve the problem.

  • If the number is odd then three number with max LCM are n, n - 1, and n - 3.

  • If the number is even and the GCM of n and n - 3 is 1 then the three numbers with max LCM are n, n - 1, and n - 3.

  • Else the three numbers with max LCM are n - 1, n - 2, and n - 3.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void threeNumbersWithMaxLCM(int n) {
   if (n % 2 != 0) {
      cout << n << " " << (n - 1) << " " << (n - 2);
   }
   else if (__gcd(n, (n - 3)) == 1) {
      cout << n << " " << (n - 1) << " " << (n - 3);
   }
   else {
      cout << (n - 1) << " " << (n - 2) << " " << (n - 3);
   }
   cout << endl;
}
int main() {
   int n = 18;
   threeNumbersWithMaxLCM(n);
   return 0;
}

Output

If you execute the above program, then you will get the following result.

17 16 15

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 29-Dec-2020 10:27:09
Advertisements