Advertisement
Nevtr4l

Test de Primalidad (Difícil)

Mar 12th, 2025 (edited)
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.49 KB | Source Code | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. using u64 = uint64_t;
  6. using u128 = __uint128_t;
  7. using ll = long long;
  8.  
  9. // Suma modular para evitar desbordamientos
  10. u64 add(u64 a, u64 b, u64 mod) {
  11.   return (u128)(a + b) % mod;
  12. }
  13.  
  14. // Multiplicación modular segura usando aritmética de enteros grandes
  15. u64 mul(u64 a, u64 b, u64 mod) {
  16.   return (u128)a * b % mod;
  17. }
  18.  
  19. // Exponenciación modular rápida: calcula (a^e) % mod en tiempo log(e)
  20. u64 fastPow(u64 a, u64 e, u64 mod) {
  21.   u64 r = 1;
  22.   a %= mod;
  23.   while (e) {
  24.     if (e & 1) r = mul(r, a, mod);
  25.     a = mul(a, a, mod);
  26.     e >>= 1;
  27.   }
  28.   return r;
  29. }
  30.  
  31. // Verifica si "a" es un testigo de que "n" no es primo
  32. bool check(u64 n, u64 a, u64 d, int s) {
  33.   u64 x = fastPow(a, d, n);
  34.   if (x == 1 || x == n - 1) return false;
  35.   for (int r = 1; r < s; r++) {
  36.     x = mul(x, x, n);
  37.     if (x == n - 1) return false;
  38.   }
  39.   return true;
  40. }
  41.  
  42. // Implementación del test de Miller-Rabin para verificar primalidad
  43. bool miller_rabin(u64 n) {
  44.   if (n < 2) return false;
  45.   int r = 0;
  46.   u64 d = n - 1;
  47.  
  48.   // Descomposición de "n - 1" en d * 2^r
  49.   while (d % 2 == 0) {
  50.     d >>= 1;
  51.     r++;
  52.   }
  53.  
  54.   // Lista de bases para el test, optimizada para números hasta 2^64
  55.   for (int a : {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37}) {
  56.     if (n == a) return true;
  57.     if (check(n, a, d, r)) return false;
  58.   }
  59.   return true;
  60. }
  61.  
  62. int main() {
  63.   ll n; cin >> n;
  64.   cout << (miller_rabin(n) ? "YES" : "NO") << endl;
  65.  
  66.   return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement