1. 程式人生 > 其它 >質因子分解

質因子分解

技術標籤:初等數論c++演算法

原理

∀N>1,若N不為素數,則有
在這裡插入圖片描述
其中p1<p2<…<pn均為素數,an均為正整數。

方法

列舉1~sqrt(n)範圍內所有素數p,判斷p是否為n的因子。是因子時,將該因子個數標記遞增,並使n=n/p,直至不是因子為止。當上述步驟結束後,若n仍大於1,則n有且僅有一個大於sqrt(n)的因子,記錄並加入陣列即可。
列舉素數時首先要找出所有的素數,這裡使用的是尤拉篩 點選檢視素數篩

程式碼實現

#include<bits/stdc++.h>
using namespace std;

int ans[1000001];
int check[
1000001]; int pri[100001]; int cnt; void euler(int n) { for(int i=2;i<=n;i++) { if(!check[i]) pri[++cnt]=i; for(int j=1;pri[j]*i<=n;j++) { check[pri[j]*i]=1; if(i%pri[j]==0) break; } } } void division(int n) { for(int i=2;i<=sqrt(n);i++) { while(n%i==0) { ans[++cnt]=i;
n=n/i; } } if(n>1) ans[++cnt]=n; } int main() { int n; scanf("%d",&n); euler(n); cnt=0; division(n); for(int i=1;i<=cnt;i++) printf("%d ",ans[i]); return 0; }