ProgrammingHardProduct company OA

What is printed?

What is printed?
char comp[31] = {0};
int cnt = 0;
for (int i = 2; i <= 30; i++) {
    if (comp[i]) continue;
    cnt++;
    for (int j = i * i; j <= 30; j += i) comp[j] = 1;
}
printf("%d", cnt);
  1. A. 11
  2. B. 10
  3. C. 9
  4. D. 15

Correct answer: B. 10

This is the sieve of Eratosthenes: each prime marks its multiples from i·i on (smaller multiples were already marked by smaller primes). The primes up to 30 are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29: 10 of them.

More C Programming questions

Exams that ask this topic