haechandev
Algorithms

[Baekjoon 1016] Square-free Numbers

A segmented sieve that marks multiples of squares within the requested interval.

August 17, 2022

Count the integers between min and max that are not divisible by any square greater than one. The start of the interval can be very large, so allocating a sieve all the way to max would waste memory.

I allocated only max - min + 1 entries and marked the positions that were multiples of each square. For a square p², the first multiple in the interval is:

start = ceil(min / p²) * p²

From there, mark start, start + p², .... A separate check array prevents an already marked number from being subtracted twice.

The key was to keep only the interval the problem asks about in memory, rather than represent every smaller integer.

Problem: Baekjoon · Code: View on GitHub