Data Structures & AlgorithmsHardCodeforces Div2 C/D · Amazon SDE OA
How many primes p satisfy p ≤ 1,000,000 and p ≡ 3 (mod 4)?
How many primes p satisfy p ≤ 1,000,000 and p ≡ 3 (mod 4)?
N=10**6
s=bytearray([1])*(N+1); s[0]=0; s[1]=0
for i in range(2,int(N**0.5)+1):
if s[i]: s[i*i::i]=bytearray(len(s[i*i::i]))
print(sum(1 for p in range(N+1) if s[p] and p%4==3))What is printed?- A. 4808
- B. 39175
- C. 39322
- D. 19653
Correct answer: C. 39322
A sieve marks composites, then the count is taken over primes in the residue class 3 mod 4. Counting class 1 mod 4 is a different count, shrinking the bound changes the answer, and mixing up mod 4 with mod 8 misclassifies many primes.
More Coding Interview Problems questions
- The recursive extended Euclidean algorithm eg(a, b) returns (g, x, y) with a·x + b·y = g, using eg(a, b) = (g, y, x − (a//b)·y) when b ≠ 0…
- Matrix chain: matrices A1..A6 have dimension sequence p = [30, 35, 15, 5, 10, 20, 25] (Ai is p[i−1] × p[i]). What is the minimum number of…
- Game of two eggs and 100 floors: you have two identical eggs and must find the highest floor from which a dropped egg survives, using as…
- Array b = [9, 2, 7, 4, 1, 8, 3]. Count the pairs (i < j) with b[i] > 2·b[j] (a reverse pair). Run the brute-force code. python…
- For the array c = [1, 2, 3, 4], consider every non-empty subarray and its XOR value. How many subarrays have an XOR value that is strictly…
- For the string "character", find the length of its longest palindromic subsequence (characters need not be adjacent, but must keep their…