C Program
/* C - LCM of two integers (input: 12 18) */ #include <stdio.h> #include <stdlib.h> long long gcd(long long a, long long b){ a = llabs(a); b = llabs(b); while (b) { long long t = a % b; a = b; b = t; } return a; } int main() { long long a, b; if (scanf("%lld %lld", &a, &b) != 2) return 0; if (a == 0 || b == 0) { printf("LCM is 0\n"); return 0; } long long g = gcd(a,b); long long l = llabs(a / g * b); printf("LCM of %lld and %lld is %lld\n", a, b, l); return 0; }
C Output
Input:
12 18Output:
LCM of 12 and 18 is 36
C++ Program
// C++ - LCM of two integers (input: 8 20) #include <iostream> #include <cstdlib> using namespace std; long long gcd(long long a, long long b){ a = llabs(a); b = llabs(b); while (b) { long long t = a % b; a = b; b = t; } return a; } int main(){ long long a,b; if(!(cin>>a>>b)) return 0; if(a==0 || b==0){ cout<<"LCM is 0\n"; return 0; } long long g = gcd(a,b); long long l = llabs(a / g * b); cout<<"LCM of "<<a<<" and "<<b<<" is "<<l<<"\n"; return 0; }
C++ Output
Input:
8 20Output:
LCM of 8 and 20 is 40
JAVA Program
// Java - LCM of two integers (input: 7 3) import java.util.*; public class Main { static long gcd(long a, long b){ a = Math.abs(a); b = Math.abs(b); while (b != 0) { long t = a % b; a = b; b = t; } return a; } public static void main(String[] args){ Scanner sc = new Scanner(System.in); if(!sc.hasNextLong()) return; long a = sc.nextLong(), b = sc.nextLong(); if (a == 0 || b == 0) { System.out.println("LCM is 0"); return; } long g = gcd(a,b); long l = Math.abs(a / g * b); System.out.println("LCM of " + a + " and " + b + " is " + l); } }
JAVA Output
Input:
7 3Output:
LCM of 7 and 3 is 21
Python Program
# Python - LCM of two integers (input: 21 6) import sys data = sys.stdin.read().strip().split() if len(data) < 2: sys.exit() a, b = int(data[0]), int(data[1]) def gcd(x,y): x, y = abs(x), abs(y) while y: x, y = y, x % y return x if a == 0 or b == 0: print("LCM is 0") else: g = gcd(a,b) l = abs(a // g * b) print(f"LCM of {a} and {b} is {l}")
Python Output
Input:
21 6Output:
LCM of 21 and 6 is 42
In-Depth Learning – Entire Concept in Paragraphs
Social Plugin