Don said:
(e-mail address removed) wrote:
.... snip ...
#include <stdio.h>
/* This program implements a blindingly fast O(n^n) algorithm
to find prime numbers, using an elegant recursive method.
If n is prime it returns n. Otherwise it returns nothing (zero).
*/
int _(int n, int m, int d, int t=0)
{
int r;
if (t) return d?1+_(n,m,d-1,d):n?_(n-1,m,m,n):0;
for(r=m!=n; d*(t<n); ++t)
r &= _(n,_(t,m,0,1),d-1)|!_(t,1,t);
return r*n;
}
/*------------------------------------------
Print primes up to the requested value
--------------------------------------------*/
int main(int argc, char* argv[])
{
int n;
for(n = 2; n <= 1000; n++)
printf("Calling with input %d returns %d\n",n, _(n,1,n,0));
return 0;
}
After slight modification to make it compile (below) I can vouch
that it seems to perform as advertised for all inputs up to 5. 6
may be alright, but I didn't have the patience to wait for it.
Maybe someone will analyze the O() of the routine?
#include <stdio.h>
/* This program implements a blindingly fast O(n^n) algorithm
to find prime numbers, using an elegant recursive method.
If n is prime it returns n. Otherwise it returns nothing
(zero). By Don Dodson.
*/
static int _(int n, int m, int d, int t) {
int r;
if (t) return d ? 1 + _(n, m, d-1, d)
: n ? _(n-1, m, m, n) : 0;
for (r = m != n; d * (t < n); ++t)
r &= _(n, _(t, m, 0, 1), d-1, 0) | !_(t, 1, t, 0);
return r * n;
}
/*------------------------------------------
Print primes up to the requested value
--------------------------------------------*/
int main(int argc, char* argv[])
{
int n;
for(n = 2; n <= 1000; n++)
printf("Calling with input %d returns %d\n",
n, _(n, 1, n, 0));
return 0;
}