The Wayback Machine - https://web.archive.org/web/20241001003543/https://www.geeksforgeeks.org/lcm-of-given-array-elements/
Open In App

LCM of given array elements

Last Updated : 04 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Show Topics
Solve Problem
Basic
28.54%
6.3K

Given an array of n numbers, find the LCM of it. 

 Example:

Input : {1, 2, 8, 3}
Output : 24

Input : {2, 7, 3, 9, 4}
Output : 252

Method 1 :

We know, LCM(a, b)=\frac{a*b}{gcd(a, b)}
The above relation only holds for two numbers, 
LCM(a, b, c)\neq \frac{a*b*c}{gcd(a, b, c)}

The idea here is to extend our relation for more than 2 numbers. Let’s say we have an array arr[] that contains n elements whose LCM needed to be calculated.

The main steps of our algorithm are: 

  1. Initialize ans = arr[0].
  2. Iterate over all the elements of the array i.e. from i = 1 to i = n-1 
    At the ith iteration ans = LCM(arr[0], arr[1], …….., arr[i-1]). This can be done easily as LCM(arr[0], arr[1], …., arr[i]) = LCM(ans, arr[i]). Thus at i’th iteration we just have to do ans = LCM(ans, arr[i]) = ans x arr[i] / gcd(ans, arr[i]) 
     

Below is the implementation of the above algorithm : 

C++

// C++ program to find LCM of n elements
#include <bits/stdc++.h>
using namespace std;
 
typedef long long int ll;
 
// Utility function to find
// GCD of 'a' and 'b'
int gcd(int a, int b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
 
// Returns LCM of array elements
ll findlcm(int arr[], int n)
{
    // Initialize result
    ll ans = arr[0];
 
    // ans contains LCM of arr[0], ..arr[i]
    // after i'th iteration,
    for (int i = 1; i < n; i++)
        ans = (((arr[i] * ans)) /
                (gcd(arr[i], ans)));
 
    return ans;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 7, 3, 9, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("%lld", findlcm(arr, n));
    return 0;
}

                    

Java

// Java Program to find LCM of n elements
import java.io.*;
 
public class GFG {
     
    public static long lcm_of_array_elements(int[] element_array)
    {
        long lcm_of_array_elements = 1;
        int divisor = 2;
         
        while (true) {
            int counter = 0;
            boolean divisible = false;
             
            for (int i = 0; i < element_array.length; i++) {
 
                // lcm_of_array_elements (n1, n2, ... 0) = 0.
                // For negative number we convert into
                // positive and calculate lcm_of_array_elements.
 
                if (element_array[i] == 0) {
                    return 0;
                }
                else if (element_array[i] < 0) {
                    element_array[i] = element_array[i] * (-1);
                }
                if (element_array[i] == 1) {
                    counter++;
                }
 
                // Divide element_array by devisor if complete
                // division i.e. without remainder then replace
                // number with quotient; used for find next factor
                if (element_array[i] % divisor == 0) {
                    divisible = true;
                    element_array[i] = element_array[i] / divisor;
                }
            }
 
            // If divisor able to completely divide any number
            // from array multiply with lcm_of_array_elements
            // and store into lcm_of_array_elements and continue
            // to same divisor for next factor finding.
            // else increment divisor
            if (divisible) {
                lcm_of_array_elements = lcm_of_array_elements * divisor;
            }
            else {
                divisor++;
            }
 
            // Check if all element_array is 1 indicate
            // we found all factors and terminate while loop.
            if (counter == element_array.length) {
                return lcm_of_array_elements;
            }
        }
    }
     
    // Driver Code
    public static void main(String[] args)
    {
        int[] element_array = { 2, 7, 3, 9, 4 };
        System.out.println(lcm_of_array_elements(element_array));
    }
}
 
// Code contributed by Mohit Gupta_OMG

                    

Python

# Python Program to find LCM of n elements
 
def find_lcm(num1, num2):
    if(num1>num2):
        num = num1
        den = num2
    else:
        num = num2
        den = num1
    rem = num % den
    while(rem != 0):
        num = den
        den = rem
        rem = num % den
    gcd = den
    lcm = int(int(num1 * num2)/int(gcd))
    return lcm
     
l = [2, 7, 3, 9, 4]
 
num1 = l[0]
num2 = l[1]
lcm = find_lcm(num1, num2)
 
for i in range(2, len(l)):
    lcm = find_lcm(lcm, l[i])
     
print(lcm)
 
# Code contributed by Mohit Gupta_OMG

                    

C#

// C# Program to find LCM of n elements
using System;
 
public class GFG {
     
    public static long lcm_of_array_elements(int[] element_array)
    {
        long lcm_of_array_elements = 1;
        int divisor = 2;
         
        while (true) {
             
            int counter = 0;
            bool divisible = false;
            for (int i = 0; i < element_array.Length; i++) {
 
                // lcm_of_array_elements (n1, n2, ... 0) = 0.
                // For negative number we convert into
                // positive and calculate lcm_of_array_elements.
                if (element_array[i] == 0) {
                    return 0;
                }
                else if (element_array[i] < 0) {
                    element_array[i] = element_array[i] * (-1);
                }
                if (element_array[i] == 1) {
                    counter++;
                }
 
                // Divide element_array by devisor if complete
                // division i.e. without remainder then replace
                // number with quotient; used for find next factor
                if (element_array[i] % divisor == 0) {
                    divisible = true;
                    element_array[i] = element_array[i] / divisor;
                }
            }
 
            // If divisor able to completely divide any number
            // from array multiply with lcm_of_array_elements
            // and store into lcm_of_array_elements and continue
            // to same divisor for next factor finding.
            // else increment divisor
            if (divisible) {
                lcm_of_array_elements = lcm_of_array_elements * divisor;
            }
            else {
                divisor++;
            }
 
            // Check if all element_array is 1 indicate
            // we found all factors and terminate while loop.
            if (counter == element_array.Length) {
                return lcm_of_array_elements;
            }
        }
    }
     
    // Driver Code
    public static void Main()
    {
        int[] element_array = { 2, 7, 3, 9, 4 };
        Console.Write(lcm_of_array_elements(element_array));
    }
}
 
// This Code is contributed by nitin mittal

                    

PHP

<?php
// PHP program to find LCM of n elements
 
// Utility function to find
// GCD of 'a' and 'b'
function gcd($a, $b)
{
    if ($b == 0)
        return $a;
    return gcd($b, $a % $b);
}
 
// Returns LCM of array elements
function findlcm($arr, $n)
{
     
    // Initialize result
    $ans = $arr[0];
 
    // ans contains LCM of
    // arr[0], ..arr[i]
    // after i'th iteration,
    for ($i = 1; $i < $n; $i++)
        $ans = ((($arr[$i] * $ans)) /
                (gcd($arr[$i], $ans)));
 
    return $ans;
}
 
// Driver Code
$arr = array(2, 7, 3, 9, 4 );
$n = sizeof($arr);
echo findlcm($arr, $n);
 
// This code is contributed by ChitraNayal
?>

                    

Javascript

<script>
 
// Javascript program to find LCM of n elements
 
// Utility function to find
// GCD of 'a' and 'b'
function gcd(a, b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
 
// Returns LCM of array elements
function findlcm(arr, n)
{
    // Initialize result
    let ans = arr[0];
 
    // ans contains LCM of arr[0], ..arr[i]
    // after i'th iteration,
    for (let i = 1; i < n; i++)
        ans = (((arr[i] * ans)) /
                (gcd(arr[i], ans)));
 
    return ans;
}
 
// Driver Code
  
    let arr = [ 2, 7, 3, 9, 4 ];
    let n = arr.length;
    document.write(findlcm(arr, n));
 
// This code is contributed by Mayank Tyagi
 
</script>

                    

Output
252

Time Complexity: O(n * log(min(a, b))), where n represents the size of the given array.
Auxiliary Space: O(n*log(min(a, b))) due to recursive stack space.

Below is the implementation of the above algorithm Recursively :

C++

#include <bits/stdc++.h>
using namespace std;
 
//recursive implementation
int LcmOfArray(vector<int> arr, int idx){
    // lcm(a,b) = (a*b/gcd(a,b))
    if (idx == arr.size()-1){
        return arr[idx];
    }
    int a = arr[idx];
    int b = LcmOfArray(arr, idx+1);
    return (a*b/__gcd(a,b)); // __gcd(a,b) is inbuilt library function
}
 
 
int main() {
     
    vector<int> arr = {1,2,8,3};
    cout << LcmOfArray(arr, 0) << "\n";
      arr = {2,7,3,9,4};
      cout << LcmOfArray(arr,0) << "\n";
    return 0;
}

                    

Java

import java.util.*;
import java.io.*;
 
class GFG
{
 
  // Recursive function to return gcd of a and b 
  static int __gcd(int a, int b) 
  { 
    return b == 0? a:__gcd(b, a % b);    
  }
 
  // recursive implementation
  static int LcmOfArray(int[] arr, int idx)
  {
 
    // lcm(a,b) = (a*b/gcd(a,b))
    if (idx == arr.length - 1){
      return arr[idx];
    }
    int a = arr[idx];
    int b = LcmOfArray(arr, idx+1);
    return (a*b/__gcd(a,b)); //
  }
 
 
  public static void main(String[] args)
  {
 
    int[] arr = {1,2,8,3};
    System.out.print(LcmOfArray(arr, 0)+ "\n");
    int[]  arr1 = {2,7,3,9,4};
    System.out.print(LcmOfArray(arr1,0)+ "\n");
  }
}
 
// This code is contributed by gauravrajput1

                    

Python3

def __gcd(a, b):
    if (a == 0):
        return b
    return __gcd(b % a, a)
 
# recursive implementation
def LcmOfArray(arr, idx):
   
    # lcm(a,b) = (a*b/gcd(a,b))
    if (idx == len(arr)-1):
        return arr[idx]
    a = arr[idx]
    b = LcmOfArray(arr, idx+1)
    return int(a*b/__gcd(a,b)) # __gcd(a,b) is inbuilt library function
 
arr = [1,2,8,3]
print(LcmOfArray(arr, 0))
arr = [2,7,3,9,4]
print(LcmOfArray(arr,0))
 
# This code is contributed by divyeshrabadiya07.

                    

C#

using System;
class GFG {
     
    // Function to return
    // gcd of a and b
    static int __gcd(int a, int b)
    {
        if (a == 0)
            return b;
        return __gcd(b % a, a);
    }
  
    //recursive implementation
    static int LcmOfArray(int[] arr, int idx){
        // lcm(a,b) = (a*b/gcd(a,b))
        if (idx == arr.Length-1){
            return arr[idx];
        }
        int a = arr[idx];
        int b = LcmOfArray(arr, idx+1);
        return (a*b/__gcd(a,b)); // __gcd(a,b) is inbuilt library function
    }
     
  static void Main() {
    int[] arr = {1,2,8,3};
    Console.WriteLine(LcmOfArray(arr, 0));
    int[] arr1 = {2,7,3,9,4};
    Console.WriteLine(LcmOfArray(arr1,0));
  }
}

                    

Javascript

<script>
 
    // Function to return
    // gcd of a and b
    function __gcd(a, b)
    {
        if (a == 0)
            return b;
        return __gcd(b % a, a);
    }
 
    //recursive implementation
    function LcmOfArray(arr, idx){
        // lcm(a,b) = (a*b/gcd(a,b))
        if (idx == arr.length-1){
            return arr[idx];
        }
        let a = arr[idx];
        let b = LcmOfArray(arr, idx+1);
        return (a*b/__gcd(a,b)); // __gcd(a,b) is inbuilt library function
    }
     
    let arr = [1,2,8,3];
    document.write(LcmOfArray(arr, 0) + "</br>");
    arr = [2,7,3,9,4];
    document.write(LcmOfArray(arr,0));
 
// This code is contributed by decode2207.
</script>

                    

Output
24
252

Time Complexity: O(n * log(max(a, b)), where n represents the size of the given array.
Auxiliary Space: O(n) due to recursive stack space. 

Method 3: This code uses the reduce function from the functools library and the gcd function from the math library to find the LCM of a list of numbers. The reduce function applies the lambda function to the elements of the list, cumulatively reducing the list to a single value (the LCM in this case). The lambda function calculates the LCM of two numbers using the same approach as the previous implementation. The final LCM is returned as the result.

C++

#include <iostream>
#include <vector>
#include <numeric> // for std::accumulate
 
int gcd(int a, int b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
 
int lcm(std::vector<int> numbers)
{
    return std::accumulate(numbers.begin(), numbers.end(), 1,
        [](int x, int y) { return (x * y) / gcd(x, y); });
}
 
int main()
{
    std::vector<int> numbers = {2, 3, 4, 5};
    int LCM = lcm(numbers);
    std::cout << "LCM of " << numbers.size() << " numbers is " << LCM << std::endl;
    return 0;
}

                    

Java

// Java code to find LCM of given numbers using reduce()
// function
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
 
class Main {
    static int lcm(List<Integer> numbers)
    {
        return numbers.stream().reduce(
            1, (x, y) -> (x * y) / gcd(x, y));
    }
 
    static int gcd(int a, int b)
    {
        if (b == 0)
            return a;
        return gcd(b, a % b);
    }
 
    public static void main(String[] args)
    {
        List<Integer> numbers = Arrays.asList(2, 3, 4, 5);
        int LCM = lcm(numbers);
        System.out.println("LCM of " + numbers + " is "
                           + LCM);
    }
}

                    

Python3

from functools import reduce
import math
 
def lcm(numbers):
    return reduce(lambda x, y: x * y // math.gcd(x, y), numbers, 1)
 
numbers = [2, 3, 4, 5]
print("LCM of", numbers, "is", lcm(numbers))

                    

C#

using System;
using System.Linq;
 
class Program
{
    static int Lcm(int[] numbers)
    {
        return numbers.Aggregate((x, y) => x * y / Gcd(x, y));
    }
 
    static int Gcd(int a, int b)
    {
        if (b == 0)
            return a;
        return Gcd(b, a % b);
    }
 
    static void Main()
    {
        int[] numbers = { 2, 3, 4, 5 };
        int lcm = Lcm(numbers);
        Console.WriteLine("LCM of {0} is {1}", string.Join(", ", numbers), lcm);
    }
}

                    

Javascript

function lcm(numbers) {
  function gcd(a, b) {
    // If the second argument is 0, return the first argument (base case)
    if (b === 0) {
      return a;
    }
    // Otherwise, recursively call gcd with arguments b and the remainder of a divided by b
    return gcd(b, a % b);
  }
  // Reduce the array of numbers by multiplying each number together and dividing by their gcd
  // This finds the Least Common Multiple (LCM) of the numbers in the array
  return numbers.reduce((a, b) => a * b / gcd(a, b));
}
 
// array
let numbers = [2, 3, 4, 5];
 
// Call the lcm function
let lcmValue = lcm(numbers);
 
// Print the Output
console.log(`LCM of ${numbers.join(', ')} is ${lcmValue}`);

                    

Output
LCM of 4 numbers is 60

The time complexity of the program is O(n log n)

The auxiliary space used by the program is O(1) 

Method 4: Using Euclidean algorithm 

The function starts by initializing the lcm variable to the first element in the array. It then iterates through the rest of the array, and for each element, it calculates the GCD of the current lcm and the element using the Euclidean algorithm. The calculated GCD is stored in the gcd variable.

Once the GCD is calculated, the LCM is updated by multiplying the current lcm with the element and dividing by the GCD. This is done using the formula LCM(a,b) = (a * b) / GCD(a,b).

C++

#include <iostream>
#include <vector>
using namespace std;
 
int gcd(int num1, int num2)
{
    if (num2 == 0)
        return num1;
    return gcd(num2, num1 % num2);
}
 
int lcm_of_array(vector<int> arr)
{
    int lcm = arr[0];
    for (int i = 1; i < arr.size(); i++) {
        int num1 = lcm;
        int num2 = arr[i];
        int gcd_val = gcd(num1, num2);
        lcm = (lcm * arr[i]) / gcd_val;
    }
    return lcm;
}
 
int main()
{
    vector<int> arr1 = { 1, 2, 8, 3 };
    vector<int> arr2 = { 2, 7, 3, 9, 4 };
    cout << lcm_of_array(arr1) << endl; // Output: 24
    cout << lcm_of_array(arr2) << endl; // Output: 252
    return 0;
}

                    

Java

import java.util.*;
 
public class Main {
 
    public static int gcd(int num1, int num2)
    {
        if (num2 == 0)
            return num1;
        return gcd(num2, num1 % num2);
    }
 
    public static int lcm_of_array(ArrayList<Integer> arr)
    {
        int lcm = arr.get(0);
        for (int i = 1; i < arr.size(); i++) {
            int num1 = lcm;
            int num2 = arr.get(i);
            int gcd_val = gcd(num1, num2);
            lcm = (lcm * arr.get(i)) / gcd_val;
        }
        return lcm;
    }
 
    public static void main(String[] args)
    {
        ArrayList<Integer> arr1
            = new ArrayList<>(Arrays.asList(1, 2, 8, 3));
        ArrayList<Integer> arr2
            = new ArrayList<>(Arrays.asList(2, 7, 3, 9, 4));
        System.out.println(
            lcm_of_array(arr1)); // Output: 24
        System.out.println(
            lcm_of_array(arr2)); // Output: 252
    }
}

                    

Python3

def lcm_of_array(arr):
    lcm = arr[0]
    for i in range(1, len(arr)):
        num1 = lcm
        num2 = arr[i]
        gcd = 1
        # Finding GCD using Euclidean algorithm
        while num2 != 0:
            temp = num2
            num2 = num1 % num2
            num1 = temp
        gcd = num1
        lcm = (lcm * arr[i]) // gcd
    return lcm
 
 
# Example usage
arr1 = [1, 2, 8, 3]
arr2 = [2, 7, 3, 9, 4]
print(lcm_of_array(arr1))  # Output: 24
print(lcm_of_array(arr2))  # Output: 252

                    

C#

using System;
using System.Collections.Generic;
 
class Program {
    static int Gcd(int num1, int num2)
    {
        if (num2 == 0)
            return num1;
        return Gcd(num2, num1 % num2);
    }
 
    static int LcmOfArray(List<int> arr)
    {
        int lcm = arr[0];
        for (int i = 1; i < arr.Count; i++) {
            int num1 = lcm;
            int num2 = arr[i];
            int gcdVal = Gcd(num1, num2);
            lcm = (lcm * arr[i]) / gcdVal;
        }
        return lcm;
    }
 
    static void Main()
    {
        List<int> arr1 = new List<int>{ 1, 2, 8, 3 };
        List<int> arr2 = new List<int>{ 2, 7, 3, 9, 4 };
        Console.WriteLine(LcmOfArray(arr1)); // Output: 24
        Console.WriteLine(LcmOfArray(arr2)); // Output: 252
    }
}

                    

Javascript

function gcd(num1, num2) {
    if (num2 == 0)
        return num1;
    return gcd(num2, num1 % num2);
}
 
function lcm_of_array(arr) {
    let lcm = arr[0];
    for (let i = 1; i < arr.length; i++) {
        let num1 = lcm;
        let num2 = arr[i];
        let gcd_val = gcd(num1, num2);
        lcm = (lcm * arr[i]) / gcd_val;
    }
    return lcm;
}
 
let arr1 = [1, 2, 8, 3];
let arr2 = [2, 7, 3, 9, 4];
console.log(lcm_of_array(arr1)); // Output: 24
console.log(lcm_of_array(arr2)); // Output: 252

                    

Output
24
252


The time complexity of the above code is O(n log n), where n is the length of the input array. This is because for each element of the array, we need to find the GCD, which has a time complexity of O(log n) using the Euclidean algorithm. Since we are iterating over n elements of the array, the overall time complexity becomes O(n log n).

The auxiliary space used by this algorithm is O(1), as only a constant number of variables are used throughout the algorithm, regardless of the size of the input array.

Related Article : 





Previous Article
Next Article

Similar Reads

Sum of LCM(1, n), LCM(2, n), LCM(3, n), ... , LCM(n, n)
Given an integer n, the task is to find the sum: LCM(1, n) + LCM(2, n) + LCM(3, n) + ... + LCM(n, n) where LCM(i, n) is the Least Common Multiple of i and n. Examples: Input: 3 Output: 10 LCM(1, 3) + LCM(2, 3) + LCM(3, 3) = 3 + 6 + 3 = 12 Input: 5 Output: 55 LCM(1, 5) + LCM(2, 5) + LCM(3, 5) + LCM(4, 5) + LCM(5, 5) = 55 Naive Approach: LCM of two n
11 min read
Find triplet (A, B, C) such that LCM(A, B) + LCM(A, C) + LCM(B, C) equals N
Given an integer N. Find a triplet let say {A, B, C} such that LCM(A, B) + LCM(B, C) + LCM(A, C) = N. If no possible triplets are there, output -1 instead. Examples: Input: N = 1Output: -1Explanation: No possible triplets are there. Input: N = 15Output: 5 5 5Explanation: LCM(5, 5) + LCM(5, 1) + LCM(5, 1) = 5 + 5 + 5 = 15. Observations: Observation
8 min read
Minimum replacement of pairs by their LCM required to reduce given array to its LCM
Given an array arr[] consisting of N positive integers, the task is to find the minimum number of pairs (arr[i], arr[j]) from the given array needed to be replaced with their LCM such that the array is reduced to a single element equal to the LCM of the initial array.Examples: Input: arr[] = {1, 2, 3, 4} Output: 3 Explanation: LCM of the array = 12
9 min read
Count Subarray of size K in given Array with given LCM
Given an array arr[] of length N, the task is to find the number of subarrays where the least common multiple (LCM) of the subarray is equal to K and the size of that subarray is S. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6}, K = 6, S = 2Output: 1Explanation: {1, 2, 3 }, {2, 3}, {6}There are 3 subarrays that can be generated from the main array wi
8 min read
Construct longest possible sequence of unique elements with given LCM
Given a positive integer N, the task is to construct the longest sorted sequence of unique elements whose LCM of the is equal to N. Examples: Input: N = 12 Output: 1 2 3 4 6 12 Explanation: LCM of {1, 2, 3, 4, 6, 12 } is N( = 12). Therefore, the longest possible sequence is {1, 2, 3, 4, 6, 12 }. Input: N = 9 Output: 1 3 9 Explanation: LCM of { 1, 2
5 min read
LCM of unique elements present in an array
Given an array arr[] consisting of N positive integers, the task is to find the LCM of all unique elements of the given array. If the array does not contain any unique elements, then print "-1". Examples: Input: arr[] = {1, 2, 1, 3, 3, 4}Output: 4Explanation: The unique elements of the given array are: 2 and 4. Therefore, the LCM of (2, 4) is 4. In
8 min read
Prime factors of LCM of array elements
Given an array arr[] such that 1 <= arr[i] <= 10^12, the task is to find prime factors of LCM of array elements. Examples: Input : arr[] = {1, 2, 3, 4, 5, 6, 7, 8} Output : 2 3 5 7 // LCM of n elements is 840 and 840 = 2*2*2*3*5*7 // so prime factors would be 2, 3, 5, 7 Input : arr[] = {20, 10, 15, 60} Output : 2 3 5 // LCM of n elements is 6
15+ min read
Check if LCM of array elements is divisible by a prime number or not
Given an array and a number k, the task is to find if LCM of the array is divisible by k or not.Examples : Input : int[] a = {10, 20, 15, 25} k = 3 Output : true Input : int[] a = {24, 21, 45, 57, 36}; k = 23; Output : false One simple solution is to first find LCM of array elements, then check if LCM is divisible by k or not.Here, without calculat
5 min read
Remove an element to minimize the LCM of the given array
Given an array arr[] of length N ? 2. The task is to remove an element from the given array such that the LCM of the array after removing it is minimized.Examples: Input: arr[] = {18, 12, 24} Output: 24 Remove 12: LCM(18, 24) = 72 Remove 18: LCM(12, 24) = 24 Remove 24: LCM(12, 18) = 36Input: arr[] = {5, 15, 9, 36} Output: 45 Approach: Idea is to fi
8 min read
Maximum LCM among all pairs (i, j) from the given Array
Given an array arr[], the task is to find the maximum LCM when the elements of the array are taken in pairs. Examples: Input: arr[] = {17, 3, 8, 6} Output: 136 Explanation: Respective Pairs with their LCM are: {8, 17} has LCM 136, {3, 17} has LCM 51, {6, 17} has LCM 102, {3, 8} has LCM 24, {3, 6} has LCM 6, and {6, 8} has LCM 24. Maximum LCM among
9 min read
Minimum LCM of all pairs in a given array
Given an array arr[] of size N, the task is to find the minimum LCM (Least Common Multiple) of all unique pairs in the given array, where 1 <= N <= 105, 1 <= arr[i] <= 105. Examples: Input: arr[] = {2, 4, 3} Output: 4 Explanation LCM (2, 4) = 4 LCM (2, 3) = 6 LCM (4, 3) = 12 Minimum possible LCM is 4. Input: arr [] ={1, 5, 2, 2, 6} Outp
12 min read
Find the subset of Array with given LCM
Given an array arr[] consisting of N positive integers and a positive integer X, the task is to find the subset of the given array whose Lowest Common Multiple(LCM) is X. If there doesn't exists any subset then print "-1". Examples: Input: arr[ ] = {2, 4, 3, 5}, X = 20Output: {4, 5}Explanation:Consider the subset {4, 5}, the LCM of this subset is 2
8 min read
Number of ways to change the Array such that largest element is LCM of array
Given an array arr[] , the task is to count the number of the unique arrays can be formed by updating the elements of the given array to any element in the range [1, arr[i]] such that the Least common multiple of the updated array is equal to the maximum element. Examples: Input: arr[] = {6, 3} Output: 13 Explanation: Possible Arrays are - {[1, 1],
15+ min read
Find any pair with given GCD and LCM
Given gcd G and lcm L. The task is to print any pair which has gcd G and lcm L.Examples: Input: G = 3, L = 12 Output: 3, 12 Input: G = 1, L = 10 Output: 1, 10 A normal solution will be to perform iteration over all the factor pairs of g*l and check if any pair has gcd g and lcm as l. If they have, then the pair will be the answer.Below is the imple
8 min read
Find the other number when LCM and HCF given
Given a number A and L.C.M and H.C.F. The task is to determine the other number B. Examples: Input: A = 10, Lcm = 10, Hcf = 50. Output: B = 50 Input: A = 5, Lcm = 25, Hcf = 4. Output: B = 20 Formula: A * B = LCM * HCF B = (LCM * HCF)/AExample : A = 15, B = 12 HCF = 3, LCM = 60 We can see that 3 * 60 = 15 * 12. How does this formula work? Since HCF
4 min read
Find two distinct numbers such that their LCM lies in given range
Given two numbers L and R, the task is to find two distinct minimum positive integers X and Y such that whose LCM lies in the range [L, R]. If there doesn't exist any value of X and Y then print "-1". Examples: Input: L = 3, R = 8 Output: x = 3, y=6Explanation:LCM of 3 and 6 is 6 which is in range 3, 8 Input: L = 88, R = 90Output: -1Explanation:Min
4 min read
Count ordered pairs of numbers with a given LCM
Given an integer N, the task is to count the total number of ordered pairs such that the LCM of each pair is equal to N. Examples: Input: N = 6Output: 9 Explanation: Pairs with LCM equal to N(= 6) are {(1, 6), (2, 6), (2, 3), (3, 6), (6, 6), (6, 3), (3, 2), (6, 2), (6, 1)} Therefore, the output is 9. Input: N = 36Output: 25 Brute Force Approach: A
8 min read
Minimum number to be added to minimize LCM of two given numbers
Given two numbers A and B, the task is to find the minimum number that needs to be added to A and B such that their LCM is minimized. Examples: Input: A = 6, B = 10Output: 2Explanation: On adding 2 to A and B, the value becomes 8 and 12 respectively. LCM of 8 and 12 is 24, which is the minimum LCM possible. Input: A = 5, B = 10Output: 0Explanation:
10 min read
Minimize sum of K positive integers with given LCM
Given two positive integers K and X, the task is to find the minimum possible sum of K positive integers ( repetitions allowed ) having LCM X. Examples: Input: K = 2, X = 6 Output: 5 Explanation: K(= 2) positive integers of minimum possible sum having LCM X(= 6) are { 2, 3 }. Therefore, the minimum possible sum of K(= 2) positive integers = (2 + 3)
14 min read
Minimize Y for given N to minimize difference between LCM and GCD
Given an integer N, the task is to find a minimum possible Y that satisfies the following condition: Y > N.Y is not divisible by N (except N = 1).The absolute difference of gcd and lcm of N and Y i.e. | gcd(N, Y)?lcm(N, Y) | is as minimum as possible Examples: Input: N = 3 Output: 4?Explanation: When Y = 4 is taken then GCD(3, 4) = 1 and LCM(3,
5 min read
Find the least common multiple (LCM) of given Strings
Given two strings str1 and str2 of lengths N and M respectively. The task is to find the least common multiple (LCM) of both the strings and if it doesn't exist print -1. Note: LCM of two strings is a string that can be formed by concatenating the strings to themselves and is shortest in length. Examples: Input: str1 = "baba", str2 = "ba"Output: ba
4 min read
Find two numbers with given sum and maximum possible LCM
Given an integer X, the task is to find two integers A and B such that sum of these two numbers is X and the LCM of A and B is maximum. Examples: Input: X = 15Output: 7 8Explanation: 7 + 8 = 15 and LCM(7, 8) = 56 is the maximum possible. Input: X = 30 Output: 13 17Explanation:13 + 17 = 30 and LCM(13, 17) = 221 is the maximum possible. Naive Approac
10 min read
Find the number of pairs with given GCD and LCM represented by prime factorization
Given two large number X and Y in the form of arrays as their prime factorization of size N and M. X = A[1]B[1] * A[2]B[2] * A[3]B[3] * ....... * A[N]B[N] and Y = C[1]D[1] * C[2]D[2] * C[3] D[3] * ..... * C[M]D[M], the task for this problem is to find out the number of pairs (a, b) such that LCM(a, b) is X and GCD(a, b) is Y. Since the number of pa
10 min read
LCM of digits of a given number
Given a number n, find the LCM of its digits. Examples: Input : 397 Output : 63 LCM of 3, 9 and 7 is 63. Input : 244 Output : 4 LCM of 2, 4 and 4 is 4. Method 1: Follow the steps to solve this problem: Initialise a variable l = 1While n is greater than 0. Do the following:Find the LCM of n % 10 and lcmCheck if lcm == 0 , return 0Initialise n = n /
5 min read
Given GCD G and LCM L, find number of possible pairs (a, b)
We need to find number of possible pairs (a, b) such that GCD(a, b) is equal to given G and LCM (a, b) such that LCM(a, b) is equal to given L.Examples: Input : G = 2, L = 12 Output : 4 Explanation : There are 4 possible pairs : (2, 12), (4, 6), (6, 4), (12, 2) Input : G = 3, L = 6 Output : 2 Explanation : There are 2 possible pairs : (3, 6), (6, 3
14 min read
Count pairs in an array such that LCM(arr[i], arr[j]) > min(arr[i],arr[j])
Given an array arr[], the task is to find the count of pairs in the array such that LCM(arr[i], arr[j]) > min(arr[i], arr[j]) Note: Pairs (arr[i], arr[j]) and (arr[j], arr[i]) are considered identical and will be counted only once. Examples: Input: arr[] = {1, 1, 4, 9} Output: 5 All valid pairs are (1, 4), (1, 9), (1, 4), (1, 9) and (4, 9). Inpu
9 min read
Find element that maximizes LCM of an Array in the range 1 to M
Given an array arr of size N containing numbers in the range [1, M], the task is to find an element, in the range [1, M], which maximises the LCM.Examples: Input: arr[]={3, 4, 2, 7}, M = 8 Output: 5 Explanation: The LCM of existing array (3, 4, 2, 7) = 84 Adding the remaining numbers in 1 to 8 and check the corresponding LCM of the resulting array.
11 min read
Find the GCD of LCM of all unique pairs in an Array
Given an integer array arr[] of size N, the task is to find the GCD of LCM of all unique pair (i, j) of the array, such that i < j.Examples: Input: arr[] = {10, 24, 40, 80} Output: 40 Explanation: LCM of all unique pairs following given conditions are: LCM(10, 24) = 120 LCM(10, 40) = 40 LCM(10, 80) = 80 LCM(24, 40) = 120 LCM(24, 80) = 240 LCM(40
9 min read
Count of pairs having even and odd LCM from an array
Given an array arr[] of size N, the task is to count the number of pairs having even LCM and odd LCM. Examples: Input: arr[] = {3, 6, 5, 4}Output: Even = 5, Odd = 1Explanation: LCM of (3, 6) is 6, LCM of (3, 5) is 15, LCM of (3, 4) is 12, LCM of (6, 5) is 30, LCM of (6, 4) is 12, LCM of (5, 4) is 20.Pairs having even LCM are (3, 6), (3, 4), (6, 5),
6 min read
Count distinct pair of indices in Array whose GCD and LCM are same
Given an array A[] of length N, the task is to find the total number of distinct pairs (i, j) of indices where 1 ? i < j ? N such that the greatest common divisor(gcd) and least common multiple(lcm) of these elements are equal. Examples: Input: A[] = {2, 5, 5, 5, 6} Output: 3 ?Explanation: Here pair (i, j) are: (2, 3), (3, 4), and (2, 4). To ela
5 min read
Article Tags :
Practice Tags :