C++ 中数组元素 LCM 的质因数


在此问题中,我们得到一个范围在 1 <= arr[i] <= 1012 内的数组。我们的任务是打印数组所有元素的 LCM 的所有质因数。

让我们通过一个示例来理解我们的问题

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

要解决此问题,我们首先需要找到数组数字的 LCM,然后找到 LCM 的因子并将所有质数变成质数。

对于编译器来说,查找 10^6 数量级的数字的 LCM 可能有点吃力。因此,我们必须使用其他方法来解决它。

我们将使用数字的质因数也将是其 LCM 的质因数的概念。为此,我们将使用素因数分解并使用 Sundaram 算法找出质数。

然后生成一个因数数组,其中将包含数组数字 LCM 的质因数。

程序显示了我们的解决方案的实现

示例

 动态演示

#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;
}

输出

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

更新于: 03-Feb-2020

137 次浏览

开启你的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.