模板 - 分解质因数(试除法分解质因数、Pollard Rho因数分解、快速阶乘质因数分解)

整理的算法模板合集: ACM模板


试除法分解质因数

void divide(int x)
{
    for (int i = 2; i <= x / i; i ++ )
        if (x % i == 0)
        {
            int s = 0;
            while (x % i == 0) x /= i, s ++ ;
            cout << i << ' ' << s << endl;
        }
    if (x > 1) cout << x << ' ' << 1 << endl;
    cout << endl;
}

Pollard Rho因数分解

时间复杂度 : O n 1 4 ) O(n^\frac{1}{4})

#include "stdio.h"
#include "conio.h"
main()
{
	int n,i;
	scanf("%d",&n);
  	for(i=2;i<=n;i++)
    	while(n!=i)
      		if(n%i==0)
        		printf("%d*",i),n=n/i;
      		else break;
  printf("%d",n);
}

快速质因数分解阶乘

n ! = 1 2 3 4 . . . n n! = 1 * 2 * 3 * 4 * ...*n ,利用这一性质快速分解质因数
我们发现N!中质数因子p的个数,就是 1   N 1~N 中每个数含有的质因数p个数.既然如此的话,那么我们发现,至少有一个质因子 p p 的显然有 [ n p ] [\frac{n}{p}] 个,而至少有两个质因子p数的显然是有 [ n p 2 ] [\frac{n}{p^2}]

时间复杂度: O ( n l o g l o g n ) O(nloglogn)

/*AcWing 197. 阶乘分解
给定整数 N ,试把阶乘 N! 分解质因数,按照算术基本定理的形式输出分解结果中的 pi 和 ci 即可。*/
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 1000010;

int primes[N], cnt;
bool st[N];

void init(int n)
{
    for (int i = 2; i <= n; i ++ )
    {
        if (!st[i]) primes[cnt ++ ] = i;
        for (int j = 0; primes[j] * i <= n; j ++ )
        {
            st[i * primes[j]] = true;
            if (i % primes[j] == 0) break;
        }
    }
}

int main()
{
    int n;
    cin >> n;
    init(n);

    for (int i = 0; i < cnt; i ++ )
    {
        int p = primes[i];
        int s = 0;
        for (int j = n; j; j /= p) s += j / p;
        printf("%d %d\n", p, s);
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45697774/article/details/108248870