ProgrammingVery hard
To test whether n = 10^12 is prime by trial division up to sqrt(n), which loop is correct?
- A. for (int i = 2; i * i <= n; i++) if (n % i == 0) return 0;
- B. for (long long i = 2; i * i <= n; i++) if (n % i == 0) return 0;
- C. for (int i = 2; i <= n / i; i++) if (n % i == 0) return 0; with n as int
- 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
- A middle index of a range [lo, hi] is needed for hi near INTMAX. Which expression is safe?
- A scanf loop reads integers until the end of input. Which loop is correct when the input may end with a non-numeric token?
- A character loop reads bytes with char c = getchar() and tests while (c != EOF). Why can this loop be wrong?
- To count occurrences of values up to 10^6 in O(n), which code is correct and fast enough?
- A recursive depth-first search could recurse 10^6 levels deep on a path-shaped graph. Which approach is correct and safe?
- A string of up to 10^6 characters is read with fgets. Which buffer declaration is correct?