Prepare a sieve of prime flags
Share composite-marking work across a bounded range.
Understand the idea
Initialize a table through N and mark 0 and 1 nonprime. Process each still-prime p up to √N and mark p², p² + p, ... composite. Smaller composite multiples already have a smaller prime factor.
Trace a small example
Through 20, processing 2 removes even composites; processing 3 removes 9 and 15 among the remaining candidates. The primes are 2, 3, 5, 7, 11, 13, 17, 19. Composite 4 is skipped as a marking base.
Conditions and cost
The usual sieve costs O(N log log N) time and O(N) space. Allocate N + 1 entries, handle small limits before indexing 1, and use wide multiplication or a division guard before p*p. The table knows nothing above N.
Prefix sum explorer
Query [l, r] is zero-based and inclusive. P[k] stores the total of the first k values; P[0] is zero.
Input array a
Prefix array P
Preprocess once in O(n). Each range sum then takes O(1).
Guided simulation · Change the inputs to test your understanding.
Why begin marking prime p’s multiples at p²?
Turn the idea into code
List primes in [10, 20].
Give me a hint
Inspect flags after completing the sieve.
Show the explained solution
11, 13, 17, 19: four primes.
Your notes
Mark complete when you can explain it yourself.