1

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 don't 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 n=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.

Rebin
  • 516
  • 1
  • 6
  • 16
  • 1
    You’re looking for the [power set](https://en.wikipedia.org/wiki/Power_set) of {x⁰, x¹, …, xⁿ}. – Ry- Mar 01 '17 at 02:25
  • 2
    I think a binary counter on the right n-1 bits? – dana Mar 01 '17 at 02:29
  • @Ryan I think with the powers set on lets say n=2 I will have also [0 1 0] which it is 'x' and is not in the order of n=2 – Rebin Mar 01 '17 at 02:54
  • @dana I think you are having a valid point but I cannot understand it very well! could you elaborate on it or a pseudo code? – Rebin Mar 01 '17 at 02:55
  • 1
    @Rebin: The power set of x^0 … x^(n − 1) with x^n at the end of each, then. – Ry- Mar 01 '17 at 02:56

1 Answers1

1

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[0] = 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
}
dana
  • 17,267
  • 6
  • 64
  • 88