LCM of given array elements
Last Updated :
09 Oct, 2024
In this article, we will learn how to find the LCM of given array elements.
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, [Tex]LCM(a, b)=\frac{a*b}{gcd(a, b)} [/Tex]
The above relation only holds for two numbers,
[Tex]LCM(a, b, c)\neq \frac{a*b*c}{gcd(a, b, c)} [/Tex]
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:
- Initialize ans = arr[0].
- 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
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>
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
?>
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
Python
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>
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);
}
}
Python
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}`);
OutputLCM 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
}
}
Python
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
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 :
Unlock your potential with our DSA Self-Paced course, designed to help you master Data Structures and Algorithms at your own pace. In 90 days, you’ll learn the core concepts of DSA, tackle real-world problems, and boost your problem-solving skills, all at a speed that fits your schedule. With comprehensive lessons and practical exercises, this course will set you up for success in technical interviews and beyond.
And here's the challenge – join the Three 90 Challenge! Complete 90% of the course in 90 days, and you’ll earn a 90% refund. It's a great way to stay motivated, track your progress, and reward yourself for your dedication. Start the challenge today, and push your limits to achieve mastery in DSA!
Similar Reads
GCD (Greatest Common Divisor) Practice Problems for Competitive Programming
GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest positive integer that divides both of the numbers. Fastest way to compute GCDThe fastest way to find the Greatest Common Divisor (GCD) of two numbers is by using the Euclidean algorithm. The Euclidean algorith
4 min read
Program to Find GCD or HCF of Two Numbers
Given two numbers a and b, the task is to find the GCD of the two numbers. Note: The GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest number that divides both of them. Examples: Input: a = 20, b = 28Output: 4Explanation: The factors of 20 are 1, 2, 4, 5, 10
15+ min read
Check if two numbers are co-prime or not
Two numbers A and B are said to be Co-Prime or mutually prime if the Greatest Common Divisor of them is 1. You have been given two numbers A and B, find if they are Co-prime or not.Examples : Input : 2 3Output : Co-PrimeInput : 4 8Output : Not Co-Prime The idea is simple, we find GCD of two numbers
5 min read
GCD of more than two (or array) numbers
Given an array of numbers, find GCD of the array elements. In a previous post we find GCD of two number. Examples: Input : arr[] = {1, 2, 3}Output : 1Input : arr[] = {2, 4, 6, 8}Output : 2The GCD of three or more numbers equals the product of the prime factors common to all the numbers, but it can a
10 min read
Program to find LCM of two numbers
LCM of two numbers is the smallest number which can be divided by both numbers. Input : a = 12, b = 18Output : 3636 is the smallest number divisible by both 12 and 18 Input : a = 5, b = 11Output : 5555 is the smallest number divisible by both 5 and 11 A simple solution is to find all prime factors o
7 min read
LCM of given array elements
In this article, we will learn how to find the LCM of given array elements. Given an array of n numbers, find the LCM of it. Example: Input : {1, 2, 8, 3}Output : 24Input : {2, 7, 3, 9, 4}Output : 252Method 1 : We know, [Tex]LCM(a, b)=\frac{a*b}{gcd(a, b)} [/Tex]The above relation only holds for two
14 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
4 min read
Minimum insertions to make a Co-prime array
Given an array of N elements, find the minimum number of insertions to convert the given array into a co-prime array. Print the resultant array also.Co-prime Array : An array in which every pair of adjacent elements are co-primes. i.e, [Tex]gcd(a, b) = 1 [/Tex]. Examples : Input : A[] = {2, 7, 28}Ou
7 min read
Find the minimum possible health of the winning player
Given an array health[] where health[i] is the health of the ith player in a game, any player can attack any other player in the game. The health of the player being attacked will be reduced by the amount of health the attacking player has. The task is to find the minimum possible health of the winn
4 min read
Minimum squares to evenly cut a rectangle
Given a rectangular sheet of length l and width w. we need to divide this sheet into square sheets such that the number of square sheets should be as minimum as possible.Examples: Input :l= 4 w=6 Output :6 We can form squares with side of 1 unit, But the number of squares will be 24, this is not min
4 min read
Minimum operations to make GCD of array a multiple of k
Given an array and k, we need to find the minimum operations needed to make GCD of the array equal or multiple of k. Here an operation means either increment or decrements an array element by 1. Examples: Input : a = { 4, 5, 6 }, k = 5 Output : 2 Explanation : We can increase 4 by 1 so that it becom
8 min read
LCM of First n Natural Numbers
Given a number n such that 1 <= N <= 10^6, the Task is to Find the LCM of First n Natural Numbers. Examples: Input : n = 5 Output : 60 Input : n = 6 Output : 60 Input : n = 7 Output : 420 We strongly recommend that you click here and practice it, before moving on to the solution. We have discu
12 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 Explan
14 min read
Count numbers in range 1 to N which are divisible by X but not by Y
Given two positive integers X and Y, the task is to count the total numbers in range 1 to N which are divisible by X but not Y. Examples: Input: x = 2, Y = 3, N = 10 Output: 4 Numbers divisible by 2 but not 3 are : 2, 4, 8, 10 Input : X = 2, Y = 4, N = 20 Output : 5 Numbers divisible by 2 but not 4
10 min read
Minimum possible final health of the last monster in a game
Given N monsters, each monster has initial health h[i] which is an integer. A monster is alive if its health is greater than 0. In each turn a random monster kills another random monster, the monster which is attacked, its health reduces by the amount of health of the attacking monster. This process
6 min read
Find the maximum GCD of the siblings of a Binary Tree
Given a 2d-array arr[][] which represents the nodes of a Binary tree, the task is to find the maximum GCD of the siblings of this tree without actually constructing it. Example: Input: arr[][] = {{4, 5}, {4, 2}, {2, 3}, {2, 1}, {3, 6}, {3, 12}} Output: 6 Explanation: For the above tree, the maxi
11 min read
Check if possible to move from given coordinate to desired coordinate
Given two coordinates (x, y) and (a, b). Find if it is possible to reach (x, y) from (a, b). Only possible moves from any coordinate (i, j) are (i-j, j)(i, i-j)(i+j, j)(i, i+j) Given x, y, a, b can be negative. Examples: Input : (x, y) = (1, 1) and (a, b) = (2, 3). Output : Yes. (1, 1) -> (2, 1)
7 min read
Program to find Greatest Common Divisor (GCD) of N strings
Given an array of string arr[], the task is the Greatest Common Divisor of the given array of string. In strings 'A' and 'B', we say "B divides A" if and only if A = concatenation of B more than 1 times.Find the largest string which divides both A and B. Examples: Input: arr[] = { "GFGGFG", "GFGGFG"
13 min read
Largest subsequence having GCD greater than 1
Given an array, arr[], find the largest subsequence such that GCD of all those subsequences are greater than 1. Examples: Input: 3, 6, 2, 5, 4 Output: 3 Explanation: There are only three elements(6, 2, 4) having GCD greater than 1 i.e., 2. So the largest subsequence will be 3 Input: 10, 15, 7, 25, 9
14 min read
Subsequence of size k with maximum possible GCD
We are given an array of positive integers and an integer k. Find the maximum possible GCD of a subsequence of size k. Examples: Input : arr[] = [2, 1, 4, 6] k = 3 Output : 2 GCD of [2, 4, 6] is 2 Input : arr[] = [1, 2, 3] k = 3 Output : 1 GCD of [1, 2, 3] is 1 Method 1 Generate all the subsequences
8 min read
Minimum gcd operations to make all array elements one
Given an array A[] of size N. You can replace any number in the array with the gcd of that element with any of its adjacent elements. Find the minimum number of such operation to make the element of whole array equal to 1. If its not possible print -1. Examples: Input : A[] = {4, 8, 9} Output : 3 Ex
8 min read
GCD of elements in a given range
Given two numbers n and m. Find the biggest integer a(gcd), such that all integers n, n + 1, n + 2, ..., m are divisible by a.Examples: Input : n = 1, m = 2 Output: 1 Explanation: Here, series become 1, 2. So, the greatest no which divides both of them is 1. Input : n = 475, m = 475 Output : 475 Exp
3 min read
Count pairs of natural numbers with GCD equal to given number
Given three positive integer L, R, G. The task is to find the count of the pair (x,y) having GCD(x,y) = G and x, y lie between L and R.Examples: Input : L = 1, R = 11, G = 5 Output : 3 (5, 5), (5, 10), (10, 5) are three pair having GCD equal to 5 and lie between 1 and 11. So answer is 3. Input : L =
6 min read
Maximum GCD of all subarrays of length at least 2
Given an array arr[] of N numbers. The task is to find the maximum GCD of all subarrays of size greater than 1. Examples: Input: arr[] = { 3, 18, 9, 9, 5, 15, 8, 7, 6, 9 } Output: 9 Explanation: GCD of the subarray {18, 9, 9} is maximum which is 9.Input: arr[] = { 4, 8, 12, 16, 20, 24 } Output: 4 Ex
5 min read
Queries for GCD of all numbers of an array except elements in a given range
Given an array of n numbers and a number of queries are also given. Each query will be represented by two integers l, r. The task is to find out the GCD of all the numbers of the array excluding the numbers given in the range l, r (both inclusive) for each query.Examples: Input : arr[] = {2, 6, 9} R
10 min read
Minimum operations required to make two numbers equal
Given two integers A and B. the task is to find the minimum number of operations required to make A and B equal. In each operation, either of the below steps can be performed: Increment either A or B with its initial value.Increment both A and B with their initial value Examples: Input: A = 4, B = 1
5 min read
GCD of two numbers formed by n repeating x and y times
Given three positive integer n, x, y. The task is to print Greatest Common Divisor of numbers formed by n repeating x times and number formed by n repeating y times. 0 <= n, x, y <= 1000000000.Examples : Input : n = 123, x = 2, y = 3. Output : 123 Number formed are 123123 and 123123123. Greate
6 min read
Remove an element to maximize the GCD 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 GCD of the array after removing it is maximized. Examples: Input: arr[] = {12, 15, 18} Output: 6 Remove 12: GCD(15, 18) = 3 Remove 15: GCD(12, 18) = 6 Remove 18: GCD(12, 15) = 3 Input: arr[] = {
13 min read
Common divisors of N numbers
Given an array arr[] of N integers. The task is to find all the common divisors of all N integers.Examples Input: arr[] = {6, 90, 12, 18, 30, 18} Output: 1 2 3 6 Explanation: GCD of all the numbers is 6. Now to find all the divisors of 6, we have 6 = 1 * 6 6 = 2 * 3 Hence 1, 2, 3 and 6 the common di
7 min read
Find the number of pairs such that their gcd is equals to 1
Given an array a of size N. The task is to find the number of pairs such that gcd(a[i], a[j]) is equal to 1, where [Tex]1 \leq i < j \leq N[/Tex]. Examples: Input : a[] = {1, 2, 4, 6} Output : 3 {1, 2}, {1, 4}, {1, 6} are such pairs Input : a[] = {1, 2, 3, 4, 5, 6} Output : 11 Approach : The answ
10 min read
Program to find Nth term divisible by a or b
Given two integers [Tex]a [/Tex]and [Tex]b [/Tex]. The task is to find the Nth term which is divisible by either of [Tex]a [/Tex]or [Tex]b [/Tex]. Examples : Input : a = 2, b = 5, N = 10 Output : 16 Input : a = 3, b = 7, N = 25 Output : 57 Naive Approach: A simple approach is to traverse over all th
15+ min read
Largest number that divides x and is co-prime with y
Given two positive numbers x and y. Find the maximum valued integer a such that: a divides x i.e. x % a = 0a and y are co-prime i.e. gcd(a, y) = 1 Examples : Input : x = 15 y = 3 Output : a = 5 Explanation: 5 is the max integer which satisfies both the conditions. 15 % 5 =0 gcd(5, 3) = 1 Hence, outp
6 min read
Summation of GCD of all the pairs up to N
Given a number N, find sum of all GCDs that can be formed by selecting all the pairs from 1 to N. Examples: Input : 4 Output : 7 Explanation: Numbers from 1 to 4 are: 1, 2, 3, 4 Result = gcd(1,2) + gcd(1,3) + gcd(1,4) + gcd(2,3) + gcd(2,4) + gcd(3,4) = 1 + 1 + 1 + 1 + 2 + 1 = 7 Input : 12 Output : 1
11 min read
Calculate the Sum of GCD over all subarrays
Given an array of integers, the task is to calculate the sum of GCD of all the subarrays of an array. GCD of an array is defined as the GCD of all the elements present in it. More formally, [Tex]GCD(A[n]) = GCD(A_1, A_2, A_3....A_n) [/Tex]. Summation of all the GCDs can be defined as [Tex]\sum_{i=1}
15+ min read
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
11 min read
Count number of pairs (A <= N, B <= N) such that gcd (A , B) is B
Given a number n. We need to find the number of ordered pairs of a and b such gcd(a, b) is b itselfExamples : Input : n = 2 Output : 3 (1, 1) (2, 2) and (2, 1) Input : n = 3 Output : 5 (1, 1) (2, 2) (3, 3) (2, 1) and (3, 1) Naive approach: gcd(a, b) = b means b is a factor of a. So the total number
6 min read
Find original numbers from gcd() every pair
Given an array arr[] containing GCD of every possible pair of elements of another array. The task is to find the original numbers which are used to calculate the GCD array. For example, if original numbers are {4, 6, 8} then the given array will be {4, 2, 4, 2, 6, 2, 4, 2, 8}. Examples: Input: arr[]
9 min read
Count number of sub-sequences with GCD 1
Given an array of N numbers, the task is to count the number of subsequences that have gcd equal to 1. Examples: Input: a[] = {3, 4, 8, 16} Output: 7 The subsequences are: {3, 4}, {3, 8}, {3, 16}, {3, 4, 8}, {3, 4, 16}, {3, 8, 16}, {3, 4, 8, 16} Input: a[] = {1, 2, 4} Output: 4 A simple solution is
15+ min read
Split array into minimum number of subarrays having GCD of its first and last element exceeding 1
Given an array arr[] of size N, the task is to split the entire array into a minimum number of subarrays such that for each subarray, the GCD of the first and last element of the subarray is greater than 1. Examples: Input: arr[] = {2, 3, 4, 4, 4, 3} Output: 2 Explanation: Split the given array into
7 min read