问题
Given two numbers x
and y
, find count of numbers that are squarefree where squarefree number is one divisible by no perfect square, except 1
. For example, 10
is square-free but 18
is not, as it is divisible by 9 = 32
. Few positive square-free numbers are :
1, 2, 3, 5, 6, 7, 10, 11, 13, 14, 15 ...
limits
1 <= X,Y <= 10^9
0 <= |X-Y| <= 10^6
x=10 , Y=15
gives
ans=5
My approach is to generate all prime till squareroot(10^9)
(sieve of eratosthenes), and check whether each number in given range divisible by square of prime . Count of such numbers is substracted from length of range to give square free numbers .
But this approach time out in complexity , please suggest some other approach
回答1:
Use the inclusion-exclusion principle:
Let f(n) = number of non-square-free numbers in 1 ... n
. We will only do inclusion-exclusion on the squares of primes, so as to avoid overcounting for squares of squares.
We have:
f(n) = n / 4 => these are divisible by 4, so NOT square-free
+
n / 9 => these are divisible by 9, so NOT square-free
+
n / 25 => these are divisible by 16, so NOT square-free
+
...
-
n / (4*9) => these are divisible by both 4 and 9, so we overcounted
-
n / (4*25) => these are divisible by both 4 and 25, so we overcounted
-
...
How efficient is this?
We only need primes p
such that p^2 <= 10^9
, meaning p < 31623
. This already isn't a lot of primes, any trivial sieve (or maybe even trial division) should be fast enough. Then apply inclusion-exclusion, which will also be fast since the products of squared primes will get large fast so you'll be able to terminate prematurely in a a lot of cases (n / something = 0
whenever something > n
).
In order to see why you'll be able to terminate prematurely, rewrite the above as:
f(n) = n / (2^2) -
n / (2^2*3^2) +
n / (2^2*3^2*5^2) - <= this becomes 0 very fast.
When it does,
backtrack and increment the previous term.
For example, if this were 0,
you'd do - n / (2^2*5^2) next
...
More info on this here.
回答2:
To expand on my comment: assume that X <= Y and initialize a boolean array SF[X..Y] to be all true. For every k from 2 to floor(sqrt(Y)) (optionally including the composites; the asymptotic running time stays the same), for every multiple m of k² between X and Y, set SF[m] to false. Return the number of true values remaining in SF.
The running time is O((Y - X) + sqrt(Y)), since Σk=1,...,∞ 1/k² = π²/6.
来源:https://stackoverflow.com/questions/23044332/count-of-squarefree-numbers-in-range