 Rebin -4 years ago 101
C# Question

# Generate all polynomials with coefficients 0 or 1 given degree n

I am trying to enumerate in 'C#' all the possible polynomials given the degree. Is there any algorithm to enumerate all possible polynomials given degree n? Maybe I dont know how to ask this question precisely but these are the examples

for example:

for n=1

``````x+1    return [1 1]
x      return [1 0]
``````

for n=2

``````x^2+x+1  return [1 1 1]
x^2+x    return [1 1 0]
x^2      return [1 0 0]
x^2+1    return [1 0 1]
``````

for x=3

``````x^3           return [1 0 0 0]
x^3+x^2       return [1 1 0 0]
x^3+x         return [1 0 1 0]
x^3+x^2+x     return [1 1 1 0]
x^3+1         return [1 0 0 1]
x^3+x^2+1     return [1 1 0 1]
x^3+x+1       return [1 0 1 1]
x^3+x^2+x+1   return [1 1 1 1]
``````

Any pseudo code or algorithm would help. dana
Answer Source

Set the leftmost bit, then do a binary counter on the right n bits. You actually need n+1 bits to account for x^0, (in my first attempt I was off by 1).

You can generate an enumeration like so:

``````IEnumerable<int[]> GenPolys(int n)
{
int[] a = new int[n + 1];
a = 1;
bool ok = true;
while (ok)
{
yield return a;
ok = false;
for (int i = 1; i < a.Length; i++)
{
a[i] = 1 - a[i]; // flip the ith bit
if (a[i] == 1)
{
ok = true;
break;
}
}
}
}
``````

Usage:

``````foreach (int[] poly in GenPolys(4))
{
// your code here
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download
Latest added