Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <math.h>
- int main ()
- {
- int i, j, x;
- char *sieve = NULL;
- int *primes = NULL;
- printf("\nInput highest number: ");
- scanf ("%d", & x);
- // X is our input and size is now x.
- sieve = malloc (sizeof (*sieve) * x);
- printf ("Debug: sieve is %p\n", sieve);
- for (i = 2; i < x; i++) {
- sieve[i] = 1;
- }
- for (i = 2; i < sqrt (x); i++) {
- if (sieve[i] == 1){
- for (j =i; i * j < x; j++) {
- sieve[i * j] = 0;
- }
- }
- }
- // Print out what the sieve contains.
- for (i = 2, j = 0; i < x; i++) {
- if (sieve[i]) {
- printf ("%3d. Prime number = %d\n", ++j, i);
- }
- }
- // Fetch primes from the sieve into a compact array.
- for (i = 2, j = 0; i < x; i++) {
- if (sieve[i]) {
- primes = realloc (primes, ++j * sizeof (*primes));
- primes [j - 1] = i;
- }
- }
- printf ("Debug: primes is %p\n", primes);
- // Print out the list of primes.
- for (i = 0; i < j; i++) {
- printf ("%3d. Prime number = %d\n", i + 1, primes[i]);
- }
- primes = realloc (primes, (size_t) 0);
- printf ("Debug: primes is %p\n", primes);
- free (sieve);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement