http://www.perlmonks.org?node_id=521394


in reply to Obtaining terms in an expansion

ok, so the 2^N terms are each a product of N terms, a[i][j], where j can be 0 or 1 and i goes from 0 to N-1
ie, each one looks like, say
 a[0][0] * a[1][0] * a[2][1] * a[3][0] * ... * a[N-1][1]
So, we want do some binary magic.
how about something like:
#!/usr/bin/perl -wl use strict; use Data::Dumper; my $N = 4; my $size = 32; my $arr = [[1, 2], [3, 4], [5, 6], [7, 8]]; my @C; foreach my $m (0..2**$N - 1) { my $vec = ""; vec($vec, 0, $size) = $m; my @bits = split(//, unpack("B*", $vec)); splice(@bits, 0, $size - $N); # so @bits now contains the binary expansion of $m # with exactly $N bits, as you can verify by uncommenting # print join "::", @bits; $C[ $m ] = 1; # now we multiply the $N terms $arr->[i][j] # where j is the i-th bit in the binary expansion of $m $C[ $m ] *= $arr->[ $_ ][ $bits[$_] ] for 0..$N-1; } print Dumper \@C;

note, $size must be a power of 2, for vec to work, and unless you're on a 64-bit machine, it probably cannot be more than 32.

also, this works for $N no more than 31(32?) - but you may have other problems (memory say), if you want to go above that.

Hope this helps.