Berlekamp-Massey算法实现
作者:互联网
BM算法的C++实现:
#include <bits/stdc++.h>
using namespace std;
// a数组存储序列,MAXN定义为a的长度;更改这两处,即可将程序运行;
const int MAXN = 20;
int a[MAXN] = {1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0};
int d[MAXN + 1], L[MAXN + 1];
vector<int> f[MAXN + 1];
int temp[MAXN];
// 函数功能:BM初始化,计算 n0 及相关变量;
static int BM_init()
{
int n0;
for(int i = 0; i < MAXN; ++i)
{
if(a[i] != 0)
{
n0 = i;
break;
}
}
for(int i = 0; i <= n0; ++i)
{
d[i] = a[i];
// 压入0,表示常数 1 = x^0
f[i].push_back(0);
L[i] = 0;
}
f[n0 + 1].push_back(0);
f[n0 + 1].push_back(n0 + 1);
L[n0 + 1] = n0 + 1;
return n0;
}
// 函数功能:BM求解;
static void BM_solve(int n0)
{
for(int i = n0 + 1; i < MAXN; ++i)
{
// printf("L: %d\n", L[i]);
// for(int j = 0; j < f[i].size(); ++j)
// {
// printf("%d ", f[i][j]);
// }
// puts("\n----------------------------");
for(int j = 0; j < f[i].size(); ++j)
{
int Ln = f[i][j];
d[i] += a[i - Ln];
// 有限域2的运算
d[i] %= 2;
}
if(d[i] == 0)
{
f[i + 1] = f[i];
L[i + 1] = L[i];
}
else
{
int m = 0;
// 寻找 m
for(int j = i; ; --j)
{
if(L[j] < L[i])
{
m = j;
break;
}
}
// printf("## m : %d\n", m);
L[i + 1] = max(L[i], i + 1 - L[i]);
if((d[i] / d[m]) % 2 == 0)
{
f[i + 1] = f[i];
continue;
}
// 将两个多项式的系数放在同一个数组中,系数相重即舍弃
int len = 0;
for(int j = 0; j < f[m].size(); ++j)
{
temp[len++] = i - m + f[m][j];
}
for(int j = 0; j < f[i].size(); ++j)
{
temp[len++] = f[i][j];
}
sort(temp, temp + len);
if(temp[0] != temp[1] || len == 1)
f[i + 1].push_back(temp[0]);
for(int j = len - 1; j >= 1; --j)
{
if(temp[j] != temp[j - 1])
f[i + 1].push_back(temp[j]);
else
--j;
}
}
}
}
int main()
{
int n0 = BM_init();
// printf("n0: %d\n", n0);
BM_solve(n0);
// 输出结果
for(int i = 0; i < f[MAXN].size(); ++i)
{
if(i) printf(" + ");
if(f[MAXN][i] == 0) printf("1");
else printf("x^%d", f[MAXN][i]);
}
printf("\nL: %d\n", L[MAXN]);
return 0;
}
/*
本程序测试结果:
(1 + x^3 + x^9 + x^11, 11)
测试:
const int MAXN = 8;
int a[] = {0, 0, 1, 0, 1, 1, 0, 1};
线性综合解:(1 + x + x^2, 4)
*/
标签:Massey,temp,int,++,算法,MAXN,printf,n0,Berlekamp 来源: https://blog.csdn.net/qq_36368339/article/details/110305593