1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
#include <iostream> /* cout, cin, endl */
#include <ctime> /* clock */
#include <cmath> /* sqrt */
#include <cstdint> /* __uint128_t */
using namespace std;
/* MRT from https://de.wikipedia.org/wiki/Miller-Rabin-Test#Implementierung */
#include <cstdint>
using std::uint64_t;
bool mrt (const uint64_t n, const uint64_t a) { // n ungerade, 1 < a < n-1
if (n % 2 == 0) return false;
const uint64_t m = n - 1;
uint64_t d = m >> 1, e = 1;
while (!(d & 1)) d >>= 1, ++e;
__uint128_t p = a, q = a;
while (d >>= 1) { // exponentiere modular: p = a^d mod n
q *= q, q %= n; // quadriere modular: q = q^2 mod n
if (d & 1) p *= q, p %= n; // multipliziere modular: p = (p * q) mod n
}
if (p == 1 || p == m) return true; // n ist wahrscheinlich prim
while (--e) {
p *= p, p %= n;
if (p == m) return true;
if (p <= 1) break;
}
return false; // n ist nicht prim
}
int main()
{
unsigned long max(~0), delta2(100000), n, cnt(0);
cnt = 0; clock_t t0 = clock(); /* time(R) */
for (n = max - delta2; n < max; ++n)
if (mrt(n, 2) &&
mrt(n, 3) &&
mrt(n, 5) &&
mrt(n, 7) &&
mrt(n, 11) &&
mrt(n, 13) &&
mrt(n, 17) &&
mrt(n, 19) &&
mrt(n, 23)) cnt++;
double te = (double)( clock() - t0 ) / CLOCKS_PER_SEC; /* time(E) */
cout << "MRT counts " << cnt << " primes from " << max - delta2 << " to " << max << " within " << te << " seconds.\n";
}
|