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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP