Arrays & Hashing · Pattern 22 of 26
Math and number theory
A handful of facts solve a whole family of problems: the sieve for primes, GCD for reachability, base conversion for digits, and a counting formula instead of a loop.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Count primes, divisors or perfect squares
- Can you reach a value using only these moves?
- Digits, bases, column titles, reversing numbers
- n is huge (10⁹ or more), so the answer must be a formula
The template
// Sieve of Eratosthenes: how many primes are < n
int countPrimes(int n) {
if (n < 3) return 0;
boolean[] composite = new boolean[n];
int count = 0;
for (int i = 2; i < n; i++) {
if (composite[i]) continue;
count++;
for (long j = (long) i * i; j < n; j += i) composite[(int) j] = true;
}
return count;
}
int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } def count_primes(n): # Sieve of Eratosthenes: primes < n
if n < 3:
return 0
composite = [False] * n
count = 0
for i in range(2, n):
if composite[i]:
continue
count += 1
for j in range(i * i, n, i):
composite[j] = True
return count
def gcd(a, b):
return a if b == 0 else gcd(b, a % b) // Sieve of Eratosthenes: how many primes are < n
int countPrimes(int n) {
if (n < 3) return 0;
vector<bool> composite(n, false);
int count = 0;
for (int i = 2; i < n; i++) {
if (composite[i]) continue;
count++;
for (long long j = (long long)i * i; j < n; j += i) composite[j] = true;
}
return count;
}
int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } // Sieve of Eratosthenes: how many primes are < n
function countPrimes(n) {
if (n < 3) return 0;
const composite = new Uint8Array(n);
let count = 0;
for (let i = 2; i < n; i++) {
if (composite[i]) continue;
count++;
for (let j = i * i; j < n; j += i) composite[j] = 1;
}
return count;
}
function gcd(a, b) { return b === 0 ? a : gcd(b, a % b); } The variations
-
1Sieve of Eratosthenes
Cross out multiples of each prime starting at p². O(n log log n) for every prime below n.
-
2GCD and reachability
With jugs of a and b you can measure exactly the multiples of gcd(a, b). Working backwards with modulo turns repeated subtraction into one step.
Now you solve -
3Digits and bases
Peel digits with % 10 and / 10; build numbers with × base + digit. Base-26 column titles have no zero, so shift by one.
Now you solve -
4A formula instead of a loop
Bulb i is toggled once per divisor, so only perfect squares stay on: the answer is ⌊√n⌋. Inclusion-exclusion, |a − b| expansions and clock angles are formulas too.
Now you solve -
5More practice
More problems that use this pattern. Try them once the variations above feel easy.
Problems
Mistakes to avoid
- Starting the inner sieve loop at 2·i instead of i·i (correct but slower), or at i·i in int and overflowing.
- Reversing an integer without checking overflow before the last multiply.
- Column titles: there is no zero digit, so subtract 1 before each
% 26.
Lesson done
Next: Generate a few candidates, keep the best →Mark it done once you can write the template from memory and you have solved the worked examples yourself.