数论
转载自:https://www.cnblogs.com/zyf3855923/
找素数 Miller_Rabin
#include <bits/stdc++.h>
#define maxn 10005
using namespace std;
typedef long long LL;
const int inf= 1e9;
struct Miller_Rabin
{
LL prime[6] = {2, 3, 5, 233, 331};
LL qmul(LL x, LL y, LL mod) {
return x*y%mod;
return (x * y - (long long)(x / (long double)mod * y + 1e-3) *mod + mod) % mod;
}
LL qpow(LL a, LL n, LL mod) {
LL ret = 1;
while(n) {
if(n & 1) ret = qmul(ret, a, mod);
a = qmul(a, a, mod);
n >>= 1;
}
return ret;
}
bool check(LL p) {
if (p < 2) return 0;
if (p != 2 && p % 2 == 0) return 0;
LL s = p - 1;
while (!(s & 1)) s >>= 1;
for (int i = 0; i < 5; ++i) {
if (p == prime[i]) return 1;
LL t = s, m = qpow(prime[i], s, p);
while (t != p - 1 && m != 1 && m != p - 1) {
m = qmul(m, m, p);
t <<= 1;
}
if (m != p - 1 && !(t & 1)) return 0;
}
return 1;
}
}Mi;
该方法可认为在10^18范围内可行。
唯一分解定理的优化:
我们要的其实是n的所有素数因子,所以我们只要预先用欧拉筛打个素数表,遍历的时候就只用遍历素数了,这样可以快一点,并且可以处理1e12以内的数。
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
int prime[10000005];
int a[1000005];
bool vis[10000005];
int cnt=0;
void primejudge(int n)
{
memset(vis,false,sizeof(vis));
vis[1]=true;
int i,j;
for(i=2;i<=n;i++)
{
if(!vis[i]) prime[cnt++]=i;
for(j=0;j<cnt&&i*prime[j]<=n;j++)
{
vis[i*prime[j]]=true;
if(i%prime[j]==0) break;
}
}
}
int main()
{
primejudge(10000005);//预处理了1e7以内的素数
ll n;
int i,index=0;
scanf("%lld",&n);
for(i=0;i<cnt;i++)
{
while(n%prime[i]==0)
{
a[index++]=prime[i];
n/=prime[i];
}
if(n==1) break;
}
if(n!=1)
{
a[index++]=n;//这一步的意思是。如果遍历到了1e7的素数,n还没有变为1,那么剩下的n一定是一个素数。(前提,n<1e12)
}
for(i=0;i<index;i++)
{
if(i) printf(" ");
printf("%d",a[i]);
}
printf("\n");
return 0;
}
求因子个数(不是单单质因子)
int solve(int x) //返回因子总数
{
if(x==1) return 1;
int up=sqrt(x),count=2;
for(int i=2;i<=up;i++)
{
if(x%i==0)
{
if(i==up&&x/i==i) //如果两因子相同,则+1
count+=1;
else
count+=2;
}
}
return count;
}
快速幂
ll qpow(ll k,ll n,ll mod)
{
ll ans=1;
while(n>0)
{
if(n%2!=0) ans=ans*k%mod;
k=k*k%mod;
n/=2;
}
return ans;
}
ll inv(ll n,ll mod)
{
return qpow(n,mod-2,mod);
}
欧拉函数
bool vis[maxn];
int phi[maxn];
int prime[maxn];
int cnt=0;
void getphi(int n)
{
phi[1]=1;
for(int i=2;i<=n;i++)
{
if(!vis[i])
{
phi[i]=i-1;
prime[cnt++]=i;
}
for(int j=0;j<cnt&&prime[j]*i<=n;j++)
{
int x=prime[j];
vis[i*x]=true;
if(i%x==0)
{
phi[i*x]=phi[i]*x;
break;
} else
{
phi[i*x]=phi[i]*phi[x];
}
}
}
}