思路
用pollard_rho + miller_rabin来拆分数字,如果得到的质因子大于等于2的话就按照格式输出,否则就不是我们想要的梅森素数。
代码
/*Author : lifehappy
*/
// #pragma GCC optimize(2)
// #pragma GCC optimize(3)
// #include <bits/stdc++.h>
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <stdlib.h>
#include <time.h>
#include <cmath>
#include <vector>
#define mp make_pair
#define pb push_back
#define endl '\n'using namespace std;typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;const double pi = acos(-1.0);
const double eps = 1e-7;
const int inf = 0x3f3f3f3f;inline ll read() {ll f = 1, x = 0;char c = getchar();while(c < '0' || c > '9') {if(c == '-') f = -1;c = getchar();}while(c >= '0' && c <= '9') {x = (x << 1) + (x << 3) + (c ^ 48);c = getchar();}return f * x;
}void print(ll x) {if(x < 10) {putchar(x + 48);return ;}print(x / 10);putchar(x % 10 + 48);
}ll gcd(ll a, ll b) {return b ? gcd(b, a % b) : a;
}ll quick_mult(ll a, ll b, ll mod) {ll ans = 0;while(b) {if(b & 1) ans = (ans + a) % mod;a = (a + a) % mod;b >>= 1;}return ans;
}ll quick_pow(ll a, ll n, ll mod) {ll ans = 1;while(n) {if(n & 1) ans = quick_mult(ans, a, mod);a = quick_mult(a, a, mod);n >>= 1;} return ans;
}bool miller_rabin(ll n) {if(n == 2) return true;if(n < 2 || !(n & 1)) return false;ll s = 0, d = n - 1;while(!(d & 1)) {d >>= 1;s++;}for(int i = 1; i <= 11; i++) {ll a = rand() % (n - 2) + 2;ll now = quick_pow(a, d, n), pre = now;for(int j = 1; j <= s; j++) {now = quick_mult(now, now, n);if(now == 1 && pre != 1 && pre != n - 1) return false;pre = now;}if(now != 1) return false;}return true;
}ll pollard_rho(ll n, int c) {ll x, y, i = 1, k = 2;x = y = rand() % (n - 2) + 2;for( ; ; ) {i++;x = (quick_mult(x, x, n) + c) % n;ll g = gcd(y - x, n);if(g > 1 && g < n) return g;if(x == y) return n;if(i == k) y = x, k <<= 1;}
}vector<ll> fac;void find_fac(ll n, int k) {if(n == 1) return ;if(miller_rabin(n)) {fac.pb(n);return ;}ll p = n;int c = k;while(p >= n) p = pollard_rho(p, c--);find_fac(n / p, k);find_fac(p, k);
}int main() {// freopen("in.txt", "r", stdin);// freopen("out.txt", "w", stdout);// ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);int k;int prime[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61};while(scanf("%d", &k) != EOF) {for(int i = 0; i < 18 && prime[i] <= k ; i++) {ll n = (1ll << prime[i]) - 1;find_fac(n, 107);if(fac.size() > 1) {sort(fac.begin(), fac.end());printf("%lld ", fac[0]);for(int j = 1; j < fac.size(); j++) {printf("* %lld ", fac[j]);}printf("= %lld = ( 2 ^ %d ) - 1\n", n, prime[i]);}fac.clear();}}return 0;
}