haechandev
Algorithms

[Baekjoon 16563] Difficult Prime Factorization

Precompute primality before factoring a large batch of input numbers.

August 23, 2022

With up to one million input numbers, trying divisors from scratch for every number is expensive. I first marked composite numbers with a sieve, then divided each input by small primes and printed its factors.

Keep dividing while a prime divides the current value; otherwise move to the next prime. If the final remaining value is not one, it is also a prime factor.

The important choice here was to pay the preprocessing cost before handling many queries.

Problem: Baekjoon · Code: View on GitHub