#include <stdio.h>
int prime[100000000];
int* sieve(int A, int *n) {
*n = A; // *n always refers to cnt, so this line sets cnt = A
int *result
= (int *) malloc(*n
* sizeof(int)); // dynamically get a memory block that can hold A ints int i,j;
prime[0] = 1; // if prime[i] = 1 then i is NOT prime (strange choice of convention)
prime[1] = 1;
int k=0; // the number of primes found, initially 0
for(i = 2;i <=A; i++) // sieve loop
{
if(prime[i] == 0)
{
for(j=i*2;j<=A;j+=i)
prime[j] = 1;
}
}
for(i = 2;i <= A; i++) // loop for gathering up all found primes
{
if(prime[i]==0) // if prime[i] = 0 then it is prime
result[k++] = i; // equivalent to result[k] = i; k=k+1;
*n = k; // update cnt to hold the newly updated number of primes, which is k
}
return result; // return pointer to main
}
int main(void) {
int cnt, i; // cnt will store the number of primes found
int *res = sieve(100, &cnt);
// ^ here address of cnt is passed to sieve
// ^ res receives the pointer of the starting address of the result array
printf("Prime count is %d\n", cnt
); for(i=0; i<cnt; i++)
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CgppbnQgcHJpbWVbMTAwMDAwMDAwXTsKaW50KiBzaWV2ZShpbnQgQSwgaW50ICpuKSB7CgogICAgKm4gPSBBOyAgICAgICAgICAvLyAqbiBhbHdheXMgcmVmZXJzIHRvIGNudCwgc28gdGhpcyBsaW5lIHNldHMgY250ID0gQQogICAgaW50ICpyZXN1bHQgPSAoaW50ICopIG1hbGxvYygqbiAqIHNpemVvZihpbnQpKTsgLy8gZHluYW1pY2FsbHkgZ2V0IGEgbWVtb3J5IGJsb2NrIHRoYXQgY2FuIGhvbGQgQSBpbnRzCiAgICBpbnQgaSxqOwogICAgcHJpbWVbMF0gPSAxOyAgICAvLyBpZiBwcmltZVtpXSA9IDEgdGhlbiBpIGlzIE5PVCBwcmltZSAoc3RyYW5nZSBjaG9pY2Ugb2YgY29udmVudGlvbikKICAgIHByaW1lWzFdID0gMTsKICAgIGludCBrPTA7ICAgICAgICAgLy8gdGhlIG51bWJlciBvZiBwcmltZXMgZm91bmQsIGluaXRpYWxseSAwCiAgICBmb3IoaSA9IDI7aSA8PUE7IGkrKykgICAvLyBzaWV2ZSBsb29wCiAgICB7CiAgICAgICAgaWYocHJpbWVbaV0gPT0gMCkKICAgICAgICB7CiAgICAgICAgICAgIGZvcihqPWkqMjtqPD1BO2orPWkpCiAgICAgICAgICAgICAgcHJpbWVbal0gPSAxOwogICAgICAgIH0KICAgIH0KICAgIAogICAgZm9yKGkgPSAyO2kgPD0gQTsgaSsrKSAgLy8gbG9vcCBmb3IgZ2F0aGVyaW5nIHVwIGFsbCBmb3VuZCBwcmltZXMKICAgIHsKICAgICAgICBpZihwcmltZVtpXT09MCkgICAgIC8vIGlmIHByaW1lW2ldID0gMCB0aGVuIGl0IGlzIHByaW1lCiAgICAgICAgcmVzdWx0W2srK10gPSBpOyAgICAvLyBlcXVpdmFsZW50IHRvIHJlc3VsdFtrXSA9IGk7IGs9aysxOwogICAgICAgICpuID0gazsgICAgICAgICAgICAgLy8gdXBkYXRlIGNudCB0byBob2xkIHRoZSBuZXdseSB1cGRhdGVkIG51bWJlciBvZiBwcmltZXMsIHdoaWNoIGlzIGsKICAgIH0KICAgIHJldHVybiByZXN1bHQ7ICAgICAgICAgIC8vIHJldHVybiBwb2ludGVyIHRvIG1haW4KfQogCiAKaW50IG1haW4odm9pZCkgewogICAgaW50IGNudCwgaTsgICAvLyBjbnQgd2lsbCBzdG9yZSB0aGUgbnVtYmVyIG9mIHByaW1lcyBmb3VuZAogICAgaW50ICpyZXMgPSBzaWV2ZSgxMDAsICZjbnQpOwogICAgLy8gICAgICAgICAgICAgICAgICAgICBeIGhlcmUgYWRkcmVzcyBvZiBjbnQgaXMgcGFzc2VkIHRvIHNpZXZlCiAgICAvLyAgIF4gcmVzIHJlY2VpdmVzIHRoZSBwb2ludGVyIG9mIHRoZSBzdGFydGluZyBhZGRyZXNzIG9mIHRoZSByZXN1bHQgYXJyYXkKICAgIHByaW50ZigiUHJpbWUgY291bnQgaXMgJWRcbiIsIGNudCk7CiAgICBmb3IoaT0wOyBpPGNudDsgaSsrKQogICAgICAgIHByaW50ZigiJWQgIiwgcmVzW2ldKTsKICAgIHJldHVybiAwOwp9Cg==