Advertisement
Solingen

z12.3.cpp

Dec 22nd, 2024
17
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.11 KB | None | 0 0
  1. #include <iostream>
  2. #include "string.h"
  3. #include "array.h"
  4. using namespace std;
  5.  
  6. // Возвращаем степень полинома (индекс старшего ненулевого бита)
  7. int degree(unsigned int poly)
  8. {
  9.     if (poly == 0) return -1;
  10.     // built-in GCC: __builtin_clz(x) кол-во ведущих нулей
  11.     // степень = 31 - clz
  12.     return 31 - __builtin_clz(poly);
  13. }
  14.  
  15. // Остаток от деления A на B (полиномы над F2)
  16. unsigned int polyMod(unsigned int A, unsigned int B)
  17. {
  18.     while (A != 0 && degree(A) >= degree(B))
  19.     {
  20.         int shift = degree(A) - degree(B);
  21.         A ^= (B << shift); // XOR
  22.     }
  23.     return A;
  24. }
  25.  
  26. bool isIrreducible(unsigned int poly, int n)
  27. {
  28.     if (degree(poly) != n) return false;
  29.     for (int d = 1; d < n; d++)
  30.     {
  31.         // перебираем все полиномы степени d
  32.         unsigned int start = 1u << d;
  33.         unsigned int end   = (1u << (d+1)) - 1;
  34.         for (unsigned int test = start; test <= end; test++)
  35.         {
  36.             if (polyMod(poly, test) == 0)
  37.                 return false;
  38.         }
  39.     }
  40.     return true;
  41. }
  42.  
  43. int main()
  44. {
  45.     cout << "Введите n (<= 8 примерно): ";
  46.     int n;
  47.     cin >> n;
  48.  
  49.     unsigned int start = 1u << n;
  50.     unsigned int end   = (1u << (n+1)) - 1;
  51.  
  52.     Array<unsigned int> irreducibles;
  53.     for (unsigned int poly = start; poly <= end; poly++)
  54.     {
  55.         if (isIrreducible(poly, n))
  56.         {
  57.             irreducibles.append(poly);
  58.         }
  59.     }
  60.  
  61.     // Выводим, используя String
  62.     for (int i = 0; i < irreducibles.size(); i++)
  63.     {
  64.         unsigned int p = irreducibles[i];
  65.         String msg = "P: ";
  66.         // Построим двоичную строку
  67.         for (int b = n; b >= 0; b--)
  68.         {
  69.             char c = ((p >> b) & 1) + '0';
  70.             msg = msg + c;
  71.         }
  72.         msg = msg + " (неприводим)";
  73.         cout << msg << endl;
  74.     }
  75.  
  76.     cout << "Всего неприводимых: " << irreducibles.size() << endl;
  77.  
  78.     return 0;
  79. }
  80.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement