fork download
  1. #include <stdio.h>
  2.  
  3. int prime[100000000];
  4. int* sieve(int A, int *n) {
  5.  
  6. *n = A; // *n always refers to cnt, so this line sets cnt = A
  7. int *result = (int *) malloc(*n * sizeof(int)); // dynamically get a memory block that can hold A ints
  8. int i,j;
  9. prime[0] = 1; // if prime[i] = 1 then i is NOT prime (strange choice of convention)
  10. prime[1] = 1;
  11. int k=0; // the number of primes found, initially 0
  12. for(i = 2;i <=A; i++) // sieve loop
  13. {
  14. if(prime[i] == 0)
  15. {
  16. for(j=i*2;j<=A;j+=i)
  17. prime[j] = 1;
  18. }
  19. }
  20.  
  21. for(i = 2;i <= A; i++) // loop for gathering up all found primes
  22. {
  23. if(prime[i]==0) // if prime[i] = 0 then it is prime
  24. result[k++] = i; // equivalent to result[k] = i; k=k+1;
  25. *n = k; // update cnt to hold the newly updated number of primes, which is k
  26. }
  27. return result; // return pointer to main
  28. }
  29.  
  30.  
  31. int main(void) {
  32. int cnt, i; // cnt will store the number of primes found
  33. int *res = sieve(100, &cnt);
  34. // ^ here address of cnt is passed to sieve
  35. // ^ res receives the pointer of the starting address of the result array
  36. printf("Prime count is %d\n", cnt);
  37. for(i=0; i<cnt; i++)
  38. printf("%d ", res[i]);
  39. return 0;
  40. }
  41.  
Success #stdin #stdout 0s 392896KB
stdin
Standard input is empty
stdout
Prime count is 25
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97