ProgrammingHardTCS NQT · Infosys
A contest program must test whether n is prime for n up to 10^9 with a 1 second limit. Which method is fast enough for one query?
- A. trial division by every k from 2 to n - 1
- B. a sieve up to 10^9 rebuilt for each query
- C. trial division by every k with k * k <= n
- D. recursively test n - 1 down to 2
Correct answer: C. trial division by every k with k * k <= n
Checking divisors only up to the square root takes about 31623 steps for n = 10^9. The other options are either too slow or rebuild a huge sieve for every query.
More C Programming questions
- How many elements in the 1 to 50 range have exactly three 1 bits in binary?
- char buf[5] = "abcd"; printf("%zu", sizeof(buf) - strlen(buf)); What is printed?
- int a[5] = {0}; int p = a + 5; p[-1] = 7; printf("%d", a[4] + (a + 4)); What is printed?
- The sorted array is {1, 3, 3, 3, 7, 9}. What is the index of the first element that is at least 4?
- A qsort comparator compares double values with (x > y) - (x < y). After sorting {2.5, -1.0, 2.25}, which value is last?
- Merge sort merges two halves with n element comparisons, so T(n) = 2T(n/2) + n and T(1) = 0. What is T(8)?