Write a program to find the LCM of two numbers.
LCM: For two integers a and b denoted LCM(a,b), the LCM is the smallest positive integer that is evenly divisible by both a and b.
Example 1:
Input: a= 10,b = 24
Output: LCM is 120
Approach: Find the gcd of both numbers then LCM will be the multiplication of both numbers and divide the product with gcd.
C
#include <stdio.h>int GCD(int a, int b){if (b == 0)return a;return GCD(b, a % b);}int main(){int a = 10, b = 24;int gcd = GCD(a, b);int lcm = a * b / gcd;printf("LCM is %d", lcm);return 0;}
Java
public class LCM {public static void main(String[] args) {int a = 10;int b = 24;int lcm = (a * b) / gretestCommonDivisor(a, b);System.out.println("LCM is " + lcm);}private static int gretestCommonDivisor(int a, int b) {if (b == 0)return a;return gretestCommonDivisor(b, a % b);}}//Time Complexity: O(log(min(a,b)))
C++
#include <bits/stdc++.h>using namespace std;//Function to find GCDint GCD(int a,int b){if(b==0)return a;return GCD(b,a%b);}int main(){int a=10,b=24;int lcm=(a*b)/GCD(a,b);cout<<"LCM is "<<lcm<<"\n";return 0;}//Time Complexity: O(log(min(a,b)))
No comments:
Post a Comment