Advertisement
Solingen

z5.1.cpp

Dec 21st, 2024
21
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.40 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. // Простейшая проверка простоты (перебор до sqrt(n))
  5. bool isPrime(long long x)
  6. {
  7.     if (x < 2) return false;
  8.     for (long long i = 2; i * i <= x; i++)
  9.     {
  10.         if (x % i == 0) return false;
  11.     }
  12.     return true;
  13. }
  14.  
  15. int main()
  16. {
  17.     int N;
  18.     cout << "Сколько чисел Мерсена вывести? ";
  19.     cin >> N;
  20.  
  21.     // Выведем первые N чисел Мерсена (будем считать p = 2,3,5,7,11,...)
  22.     // 1) Найдём первые N простых p
  23.     // 2) Посчитаем 2^p - 1 и проверим, простое или нет
  24.     int countPrimes = 0;
  25.     long long current = 2;
  26.     while(countPrimes < N)
  27.     {
  28.         if (isPrime(current))
  29.         {
  30.             // current - это p
  31.             long long M = 1;
  32.             // Вычисляем 2^p
  33.             for (int i = 0; i < current; i++)
  34.             {
  35.                 M *= 2;  
  36.             }
  37.             M -= 1; // 2^p - 1
  38.  
  39.             // Проверим простоту M
  40.             bool primeM = isPrime(M);
  41.  
  42.             cout << "M(" << current << ") = 2^" << current << " - 1 = " << M;
  43.             if (primeM) cout << " (простое)\n";
  44.             else        cout << " (непростое)\n";
  45.  
  46.             countPrimes++;
  47.         }
  48.         current++;
  49.     }
  50.     return 0;
  51. }
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement