Prime number problem

You need to a number of floors in a building. There are 68 floors (numbered 1 to 64).

Conditions:
1. Can’t buy floors which numbers are prime.
2. Cannot buy floors which number contains a prime digit.
3. Can’t buy floor number 1.
4. Distance between all purchased floors must be different (i.e. you can’t buy floors 4, 6, and 8 because they both have 1 floor between them).
5. Distance between all purchased floors must be prime.

Using code or pseudocode figure out:
1. Maximum number of floors you can buy using conditions 1, 2 and 3?
2. Maximum number of floors you can buy using all conditions?

💡Strategies for Solving This Problem

Finding Primes Efficiently

Usually one of these: check if number is prime, find all primes up to n, or find nth prime. Each has different tricks. Got this at Google in 2023.

Approach 1: Check If Prime

Naive: Try dividing by all numbers from 2 to n-1. O(n) - too slow.

Better: Only check up to √n. If n has a factor larger than √n, it must also have one smaller than √n.

Even better: Check 2, then only odd numbers up to √n. O(√n).

Approach 2: Find All Primes Up To N

Sieve of Eratosthenes - the classic algorithm.

  1. Start with all numbers marked as prime
  2. For each prime p, mark all multiples of p as not prime
  3. Continue for all p up to √n

O(n log log n) time, O(n) space. Much faster than checking each number individually.

Why Sieve Works

Every composite number has a prime factor ≤ √n. So if we cross out all multiples of primes up to √n, only primes remain.

Optimizations

Start crossing out from p². All smaller multiples already crossed out by smaller primes.

Only store odd numbers (except 2). Saves half the space.

At Google

They asked "Find all primes up to 1 million." I used Sieve of Eratosthenes. Then asked "How would you optimize for space?" That's when I mentioned segmented sieve for very large ranges.

Also asked about primality testing for very large numbers - mentioned Miller-Rabin probabilistic test.

Scroll to Top