Prime factors of LCM of array elements in C++


In this problem, we are given an array within the range 1 <= arr[i] <= 1012. Our task is the print all prime factors of the LCM of all elements of the array.

Let’s take an example to understand our problem

Input: array = {2 , 5 , 15}
Output: 2 3 5
Explanation: LCM = 30
Factors of 30 = 2 * 3 * 5

To solve this problem, we will have to first find LCM of array digits and then find the factors of the LCM and prime all the prime numbers.

This can be a bit heavy for the compiler to find LCM of numbers of order 10^6. So, we will use have to use other ways to solve it.

We will use the concept that prime factors of numbers will also be then prime factors of of their LCM. For this, we will use the prime factorization and find prime numbers using sieve of Sundaram algorithm.

And then generate factor array which will contain prime factors of LCM of the numbers of the array.

Program to show the implementation of our solution

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
const int MAX = 1000000;
typedef long long int ll;
vector <int> primeNumbers;
void findPrimeNumbers() {
   int n = MAX;
   int nNew = (n)/2;
   bool marked[nNew + 100];
   memset(marked, false, sizeof(marked));
   int tmp=sqrt(n);
   for (int i=1; i<=(tmp-1)/2; i++)
      for (int j=(i*(i+1))<<1; j<=nNew; j=j+2*i+1)
         marked[j] = true;
   primeNumbers.push_back(2);
   for (int i=1; i<=nNew; i++)
   if (marked[i] == false)
   primeNumbers.push_back(2*i + 1);
}
void printPrimeLCM(ll arr[], int n ) {
   findPrimeNumbers();
   int factors[MAX] = {0};
   for (int i=0; i<n; i++) {
      ll copy = arr[i];
      int sqr = sqrt(copy);
      for (int j=0; primeNumbers[j]<=sqr; j++){
         if (copy%primeNumbers[j] == 0){
            while (copy%primeNumbers[j] == 0)
            copy = copy/primeNumbers[j];
            factors[primeNumbers[j]] = 1;
         }
      }
      if (copy > 1)
      factors[copy] = 1;
   }
   if (factors[2] == 1)
      cout<<2<<"\t";
   for (int i=3; i<=MAX; i=i+2)
      if (factors[i] == 1)
         cout<<i<<"\t";
}
int main() {
   ll arr[] = {20, 10, 15, 60};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout<<"Prime factors in the LCM of the numbers of the array are :\n";
   printPrimeLCM(arr, n);
   return 0;
}

Output

Prime factors in the LCM of the numbers of the array are :
2  3   5

Updated on: 03-Feb-2020

101 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements