xxxxxxxxxx
import java.util.*;
public class LCM {
public static long lcm(int a, int b) {
long x = (a/euclidGcd(a, b));
return x * b;
}
public static int euclidGcd(int a, int b) {
if (b == 0)
return a;
int aprime = a%b;
return euclidGcd(b, aprime);
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
System.out.println(lcm(a, b));
}
}
xxxxxxxxxx
long long gcd(long long int a, long long int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
long long lcm(ll int a, ll int b)
{
return (a / gcd(a, b)) * b;
}
// there is a math formula used in this code which you can search up about,
// but you can just use it as it is.
xxxxxxxxxx
#include <stdio.h>
int main() {
int n1, n2, i, gcd, lcm;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
for (i = 1; i <= n1 && i <= n2; ++i) {
// check if i is a factor of both integers
if (n1 % i == 0 && n2 % i == 0)
gcd = i;
}
lcm = (n1 * n2) / gcd;
printf("The LCM of two numbers %d and %d is %d.", n1, n2, lcm);
return 0;
}
xxxxxxxxxx
# Python program to find the L.C.M. of two input number
# This function computes GCD
def compute_gcd(x, y):
while(y):
x, y = y, x % y
return x
# This function computes LCM
def compute_lcm(x, y):
lcm = (x*y)//compute_gcd(x,y)
return lcm
num1 = 54
num2 = 24
print("The L.C.M. is", compute_lcm(num1, num2))
xxxxxxxxxx
#include <stdio.h>
int main() {
int x, y, res;
printf("Enter two positive integers: ");
scanf("%d %d", &x, &y);
res = (x > y) ? x : y;
while (1) {
if (res % x == 0 && res % y == 0) {
printf("The LCM obtained from %d and %d is %d.", x, y, res);
break;
}
++res;
}
return 0;
}
xxxxxxxxxx
//We write the function to find the GCD of two numbers.
//We consider the first element of the array to be the gcd of itself and iterate through
//each element of the array and update gcd with GCD of current element and previous gcd.
//We then find the LCM using the identity
// LCM*GCD = Multiplication of each number in the array
using System;
public class Program
{
public static void Main()
{
string[] input = Console.ReadLine().Split(' ');
int[] arr = Array.ConvertAll(input, int.Parse);
int[] res = GCDandLCM(arr);
Console.WriteLine("GCD is: {0}", res[0]);
Console.WriteLine("LCM is: {0}", res[1]);
}
//GCD and LCM of numbers given in an array
public static int[] GCDandLCM(int[] arr)
{
int gcd = arr[0];
for(int i=1; i<arr.Length; i++)
{
gcd = GCD(gcd, arr[i]);
}
int lcm = Multiply(arr)/gcd;
return new int[] {gcd, lcm};
}
//GCD using repetitive subtraction method
public static int GCD(int a, int b)
{
while(a!=b)
{
if(a>b) a=a-b;
else b=b-a;
}
return a;
}
public static int Multiply(int[] arr)
{
int mult = 1;
for(int i=0; i<arr.Length; i++)
{
mult*=arr[i];
}
return mult;
}
}