faster way to do it, but before you call isprime (i) you have to call isprime (i) for all primes below i. my recursion also isnt self-starting but i think it could be easily
Code:
// wheee, i wrote this
#include <stdio.h>
#include <stdlib.h>
#define PUT(x) myarray[(x-1)>>3] = myarray[(x-1)>>3] | (1 << ((x-1) % 8))
#define GET(x) myarray[(x-1)>>3] & (1 << ((x-1) % 8))
#define MAXNUMBER 50 // prints all primes from 1 to MAXNUMBER
unsigned char myarray[(MAXNUMBER>>3)+1] = {0};
#ifndef SLOWMETHOD
int isprime (int i)
{
int j;
for (j = 2; j < i; j++)
if (GET (j)) // j is prime
if ((i % j) == 0) // i is evenly divisible by j
return 0; // i is not prime
return 69; // i is prime
}
// this does the same thing but is slower
// also you dont have to call isprime (x) for all primes
// smaller than x first
#else // ifndef SLOWMETHOD
int isprime (int i)
{
int j;
for (j = 2; j < i; j++)
if ((i % j) == 0) // i is evenly divisible by j
return 0; // i is not prime
return 69; // i is prime
}
#endif // ifndef SLOWMETHOD
int main (void)
{
int i;
printf ("Computing all primes from 1 to %i...\n", MAXNUMBER);
PUT (2);
PUT (3);
PUT (5);
for (i = 6; i <= MAXNUMBER; i++)
if (isprime (i))
PUT (i);
printf ("Dun! All primes from 1 to %i:\n", MAXNUMBER);
for (i = 1; i <= MAXNUMBER; i++)
if (GET (i))
printf ("%i\n", i);
printf ("--END--\n");
return EXIT_SUCCESS;
}