質因數分解板子(可對long long大小的數進行分解)

板子(有隨機性):

#include <cstdio>
#include <iostream>
#include <cmath>
#include <map>
#include <algorithm>
using namespace std;

typedef long long ll;

const int MAX = 1e5 + 10;

ll Mult_Mod(ll a, ll b, ll m)//res=(a*b)%m
{
	a %= m;
	b %= m;
	ll res = 0;
	while (b)
	{
		if (b & 1)
			res = (res + a) % m;
		a = (a <<= 1) % m;
		b >>= 1;
	}
	return res % m;
}
ll Pow_Mod(ll a, ll b, ll m)//res=(a^b)%m
{
	ll res = 1;
	ll k = a;
	while (b)
	{
		if ((b & 1))
			res = Mult_Mod(res, k, m) % m;

		k = Mult_Mod(k, k, m) % m;
		b >>= 1;
	}
	return res % m;
}

bool Witness(ll a, ll n, ll x, ll sum)
{
	ll judge = Pow_Mod(a, x, n);
	if (judge == n - 1 || judge == 1)
		return 1;

	while (sum--)
	{
		judge = Mult_Mod(judge, judge, n);
		if (judge == n - 1)
			return 1;
	}
	return 0;
}

bool Miller_Rabin(ll n)
{
	if (n < 2)
		return 0;
	if (n == 2)
		return 1;
	if ((n & 1) == 0)
		return 0;

	ll x = n - 1;
	ll sum = 0;
	while (x % 2 == 0)
	{
		x >>= 1;
		sum++;
	}


	int times = 20;
	for (ll i = 1; i <= times; i++)
	{
		ll a = rand() % (n - 1) + 1;//取與p互質的整數a
		if (!Witness(a, n, x, sum))//費馬小定理的隨機數檢驗
			return 0;
	}
	return 1;
}
ll GCD(ll a, ll b)
{
	return b == 0 ? a : GCD(b, a % b);
}
ll Pollard_Rho(ll n, ll c)//尋找一個因子
{
	ll i = 1, k = 2;
	ll x = rand() % n;//產生隨機數x0(並控制其範圍在1 ~ x-1之間)
	ll y = x;
	while (1)
	{
		i++;
		x = (Mult_Mod(x, x, n) + c) % n;
		ll gcd = GCD(y - x, n);

		if (gcd < 0)
			gcd = -gcd;

		if (gcd > 1 && gcd < n)
			return gcd;

		if (y == x)
			return n;

		if (i == k)
		{
			y = x;
			k <<= 1;
		}
	}
}

int total;//因子的個數
ll factor[MAX];//存儲所有因子的數組,無序的
void Find_fac(ll n)//對n進行素因子分解,存入factor
{
	if (Miller_Rabin(n))//是素數就把這個素因子存起來
	{
		factor[++total] = n;
		return;
	}

	long long p = n;
	while (p >= n)//值變化,防止陷入死循環k
		p = Pollard_Rho(p, rand() % (n - 1) + 1);

	Find_fac(n / p);
	Find_fac(p);
}

typedef struct {
	ll p, num;
}Point;

Point fa[1024];

int main()
{
	ll n;
	scanf("%lld", &n);
	Find_fac(n);//輸出所有質因子(有重複)
	for (int i = 1; i <= total; i++) {
		printf("%lld ", factor[i]);
	}
	printf("\n");
	printf("\n");

	sort(factor + 1, factor + total + 1);
	ll num = 1;
	int cnt = 0;//0 - (cnt-1)
	fa[0].p = factor[1];
	factor[total + 1] = -1;
	for (int i = 2; i <= total + 1; i++) {
		if (factor[i] == factor[i - 1]) {
			num++;
		}
		else {
			fa[cnt].num = num;
			cnt++;
			num = 1;
			fa[cnt].p = factor[i];
		}
	}
	//輸出所有質因子(無重複且計數)
	for (int i = 0; i < cnt; i++) {
		printf("%lld %lld\n", fa[i].p, fa[i].num);
	}
	printf("\n");

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章