/* erat C */ #include #include(stdlib.h> #define PSIZE ((1<<8)-1) /* The maximum value of the prime number */ /* This means 2^8 - 1 by shifting 1 to the left 8 times */ #define QSIZE (1<<4) /* NB QSIZE is SQRT(PSIZE + 1) */ int *erat(){ /* we are returning a pointer hence *erat() */ char *er; /* create a pointer to an array to hold the PSIZE bytes */ int p = PSIZE-1; int *ip, *ip0, n, pd; ip0 = 0; printf("PSIZE = %i\n", p); er = calloc(PSIZE, 1); /* allocate space for the array of PSIZE bytes */ if (er == NULL){ printf("Allocation of PSIZE failed\n"); exit(EXIT FAILURE); /* Terminate gracefully */ /* Fill er[] with '0's with 'a' as the last character */ while (p--) /* this does p-1,p-2, . . 0 ( p = 0 is false in C) */ er[p] = '0'; er[PSIZE-1] = 'a'; /* Set compound numbers to '1', so that finally '0' reprents 'prime' */ for (p = 2; p < QSIZE; p++) { if (er[p - 2] == '0') { /* if a number is a prime */ n = p; pd = p + n; /* Square of the number */ while (pd < PSIZE + 1){ /* repeat while less than PSIZE + 1 */ er[pd - 2] = '1'; /* Mark it as not a prime */ pd = pd + n; /* Get the next power by adding the number */ /* This is quicker on the computer than calculating it */ } } } /* 'pd' is set to the number of primes */ for (pd = 0, n = 0; er[n] != 'a'; n++) { if (er[n] == '0') /* if number is a prime */ pd++; /* count it */ } printf("No of primes = %i\n",pd); /* 'ip' is set to point to a space of 'pd+l' 'ints' */ ip = (int *)calloc(pd + 1, sizeof(int)); if (ip == NULL) { printf("Failed to allocate pd\n"); exit(EXIT FAILURE); } n = 0; ip0 = ip; *ip = 1; while (er[n] != 'a') { /* copy primes into er */ if (er[n] == '0') *ip = n + 2; n++; } *ip = 1; free (er); /* Free memory of er so we can use the memory e1sewhere */ er = NULL; /* Set the pointer to the memory to NULL so it cannot be used again. (Unfortunately the QL does not have memory management so the error is not caught and the programme stopped by the operating system. */ return(ip0); /* Return the pointer to the primes */ } int main(void){ /* Lets show it works */ int *ip; ip = erat(); printf(Primes are:- "); while (*ip != -1) { printf("%i ",*ip); ip++; } printf("\n"); exit(EXIT SUCCESS); }