1. 程式人生 > 其它 >階乘分解——質因數分解

階乘分解——質因數分解

https://ac.nowcoder.com/acm/contest/1021/B

大意:將N!分解成質因子相乘的形式。

思路:

  1. 先看兩個數相乘得到的結果分解質因子的形式。10 = 2*5,8 = 2^{3},10*8 = 2*5*2^{3} = 2^{4}*5,所有我們只要找到相同的質因子p,p在兩者之間的分解質因子中的個數和就是相乘結果的p個個數。
  2. 擴充套件到n個數,對於某個質數p,找到[1,n]中p的倍數有多少個,也就是n/p個,還要找p^2的倍數有多少個,也就是n/(p^2)個,不乘2的原因是之前算p的倍數的時候已經算了。同理計算p^3.....,求個總和就是p的個數了。
#include <bits/stdc++.h>
#define ll long long
const int N = 1e6+7;
const int mod = 1e9+7;
const ll ds = 1e15;
const double eps = 1e-8;

using namespace std;

int vis[N];
void init(int n){
    for(int i = 2; i <= n; i++){
        if(!vis[i]){
            for(int j = i*i; j <= n; j += i){
                vis[j] = 1;
            }
        }
    }
}

void solve(){
    int n;
    scanf("%d",&n);
    init(n);
    for(int i = 2; i <= n; i++){
        if(!vis[i]){
            //cout << i << endl;
            int cnt = 0;
            for(int j = i; j <= n; j *= i){
                cnt += n/j;
            }
            cout << i << " " << cnt << endl;
        }
    }
}

int main(){
    // int t;
    // cin >> t;
    // while(t--)
        solve();
    //system("pause");
    return 0;
}