质因数分解板子(可对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");

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值