ProgrammingVery hard

To test whether n = 10^12 is prime by trial division up to sqrt(n), which loop is correct?

  1. A. for (int i = 2; i * i <= n; i++) if (n % i == 0) return 0;
  2. B. for (long long i = 2; i * i <= n; i++) if (n % i == 0) return 0;
  3. C. for (int i = 2; i <= n / i; i++) if (n % i == 0) return 0; with n as int
  4. D. for (int i = 2; i < n; i++) if (n % i == 0) return 0;

Correct answer: B. for (long long i = 2; i * i <= n; i++) if (n % i == 0) return 0;

With an int counter, i * i reaches 10^12 near the end and overflows, which is undefined. A long long counter keeps i * i exact. The last version is far too slow at 10^12.

More C Programming questions

Exams that ask this topic