质数判断

本文详细介绍了Miller_Rabin算法实现及其在判断大数素性的应用,同时探讨了PollardRho算法用于质因数分解的方法。通过具体的代码示例,展示了如何使用这些算法进行高效的大数处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

惭愧啊,打了半天的Miller_Rabin算法,老了

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

ll mul(ll x, ll y, ll P) {
  x %= P; y %= P;
  return (x * y - (ll)((long double)x * y / P + 0.5) * P + P) % P;
}

ll _pow(ll x, ll n, ll P) {
  ll ret = 1;
  for ( ; n; n >>= 1, x = mul(x, x, P)) {
    if( n & 1) {
      ret = mul(ret, x, P);
    }
  }
  return ret;
}

ll _fdp[6] = {2LL, 3LL, 13LL, 17LL, 61LL, 19260817LL};

bool MR(ll n) {
  if( n <= 1) {
    return false;
  }
  for ( int i = 0; i <= 5; ++ i) {
    if( n == _fdp[i]) {
      return true;
    }
  }
  for ( int i = 0; i <= 5; ++ i) {
    if( n % _fdp[i] == 0) {
      return false;
    }
  }
  for ( int i = 0; i <= 5; ++ i) {
    ll tmp = n - 1;
    while( !(tmp & 1)) {
      tmp >>= 1;
    }
    ll s = _pow(_fdp[i], tmp, n);
    while( s != n-1 && s != 1 && tmp != n-1) {
      tmp <<= 1, s = mul(s, s, n);
    }
    if( s != n-1 && !(tmp&1)) return false;
  }
  return true;
}

int main() {
}

质因数分解法Pollard Rho

ll PR(ll n, ll c) {
  ll i = 0,k = 2LL, x, y; 
  x = y = 1LL + rand() % (n - 1);
  while( 1) {
    x = (mul(x, x, n) + c) % n;
    ll d = __gcd((y - x + n) % n, n);
    if( d != 1 && d != n) {
      return d;
    }
    if( x == y) {
      return n;
    }
    if( ++ i == k) {
      y = x, k <<= 1;
    }
  }
}
vector<int> prim;

inline void fct(ll n) {
  if( n == 1) {
    return; 
  }
  if( MR(n)){ 
    return (void)(prim.push_back(n));
  }
  ll p = n; 
  for(int c = 233; p == n; -- c) {
    p = PR(p, c);
  }
  fct(p); fct(n / p);
}

1365853-20181025102147537-1154103779.gif

转载于:https://www.cnblogs.com/miecoku/p/9848155.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值