haechandev
Algorithms

[Baekjoon 1153] Four Primes

Precomputing primality and reducing a sum of four primes to searches for pairs.

August 20, 2022

Represent a natural number as the sum of four primes. To avoid repeatedly testing divisibility, I first marked primes up to one million with the Sieve of Eratosthenes.

Instead of searching for all four numbers at once, I checked whether the remaining sum could be made from two primes. I handled odd and even totals separately, fixed one pair, and searched for another pair that made up the remainder.

The useful idea was to make primality checks close to O(1) and split the sum into pairs, rather than enumerate every combination.

Problem: Baekjoon · Code: View on GitHub