Skip to main content
3 of 4
added 364 characters in body
Level River St
  • 26.7k
  • 4
  • 37
  • 105

#Update: C (function f), 92#

Even as a function, this is still the longest entry here. It's the first time I've passed an array of unknown length as a function argument in C, and apparently there is no way for a C function to know the length of an array passed to it, as the argument is passed as a pointer (regardless of the syntax used). Hence a second argument is required to indicate the length.

I kept the output to stdout, because setting up an integer array and returning it would almost certainly be longer.

Thanks to Dennis for the tips.

See the function f (92 characters excluding unnecessary whitespace) in the test programs below.

Output via printf

j;

f(int c,int*x){
  int p=1,i;
  for(i=c<<c;i--;p=i%c?p:!!printf("%d ",p))p*=(i/c>>i%c)&1?1:x[i%c];
}

main(int d,char**v){
  d--;
  int y[d];
  for(j=d;j--;)y[j]=atoi(v[j+1]);
  f(d,y);
}

Output via array pointer

j,q[512];

f(int c,int*x,int*p){
    for(int i=-1;++i-(c<<c);p[i/c]*=(i/c>>i%c)&1?1:x[i%c])i%c||(p[i/c]=1);
}

main(int d,char**v){
  d--;
  int y[d];
  for(j=d;j--;)y[j]=atoi(v[j+1]);
  f(d,y,q);
  for(j=1<<d;j--;)printf("%d ",q[j]);
}

#C (program),108#

excluding unnecessary whitespace.

p=1,i;
main(int c,char**v){
  c-=1;
  for(i=c<<c;i--;i%c||(printf("%d ",p),p=1))(i/c>>i%c)&1||(p*=atoi(v[i%c+1]));
}

Input from commandline, output to stdout. C isn't going to win here, but maybe I will try converting to a function tomorrow.

Basically we iterate through all 1<<c combinations of primes, with each bit of i/c being associated with the presence or absence of a particular prime in the product. The "inner loop" i%c runs through the primes, multiplying them according to the value of i/c. When i%c reaches 0, the product is output, then set to 1 for the next "outer" iteration.

curiously, printf("%d ",p,p=1) does not work (it always prints a 1.) This is not the first time I have seen odd behaviour when a value is used in a printf and assigned later in the same bracket. It is possible in this case that the second comma is not being treated as an argument separator, but rather as an operator.

Usage

$ ./a 2 3 5 7
1 2 3 6 5 10 15 30 7 14 21 42 35 70 105 210
Level River St
  • 26.7k
  • 4
  • 37
  • 105