Program to find LCM of 2 numbers without using GCD
Last Updated :
17 Jan, 2023
Finding LCM using GCD is explained here but here the task is to find LCM without first calculating GCD.
Examples:
Input: 7, 5
Output: 35
Input: 2, 6
Output: 6
The approach is to start with the largest of the 2 numbers and keep incrementing the larger number by itself till smaller number perfectly divides the resultant.
C++
#include <bits/stdc++.h>
using namespace std;
int findLCM(int a, int b)
{
int lar = max(a, b);
int small = min(a, b);
for (int i = lar; ; i += lar) {
if (i % small == 0)
return i;
}
}
int main()
{
int a = 5, b = 7;
cout << "LCM of " << a << " and "
<< b << " is " << findLCM(a, b);
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
class GfG {
public static int findLCM(int a, int b)
{
int lar = Math.max(a, b);
int small = Math.min(a, b);
for (int i = lar; ; i += lar) {
if (i % small == 0)
return i;
}
}
public static void main(String [] argc)
{
int a = 5, b = 7;
System.out.println( "LCM of " + a + " and "
+ b + " is " + findLCM(a, b));
}
}
|
Python 3
import sys
def findLCM(a, b):
lar = max(a, b)
small = min(a, b)
i = lar
while(1) :
if (i % small == 0):
return i
i += lar
a = 5
b = 7
print("LCM of " , a , " and ",
b , " is " ,
findLCM(a, b), sep = "")
|
C#
using System;
class GfG
{
public static int findLCM(int a,
int b)
{
int lar = Math.Max(a, b);
int small = Math.Min(a, b);
for (int i = lar; ; i += lar)
{
if (i % small == 0)
return i;
}
}
public static void Main()
{
int a = 5, b = 7;
Console.WriteLine("LCM of " + a +
" and " + b +
" is " +
findLCM(a, b));
}
}
|
PHP
<?php
function findLCM($a, $b)
{
$lar = max($a, $b);
$small = min($a, $b);
for ($i = $lar; ; $i += $lar)
{
if ($i % $small == 0)
return $i;
}
}
$a = 5;
$b = 7;
echo "LCM of " , $a , " and ",
$b , " is " ,
findLCM($a, $b);
?>
|
Javascript
<script>
function findLCM(a , b) {
var lar = Math.max(a, b);
var small = Math.min(a, b);
for (i = lar;; i += lar) {
if (i % small == 0)
return i;
}
}
var a = 5, b = 7;
document.write("LCM of " + a + " and " + b + " is " + findLCM(a, b));
</script>
|
Output:
LCM of 5 and 7 is 35
Time Complexity: O(max(a, b))
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...