Find the Count of Numbers Which Are Not Special Problem
#3233
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3233.
You are given 2 positive integers l and r. For any number x, all positive divisors of x except x are called the proper divisors of x.
A number is called special if it has exactly 2 proper divisors. For example:
- The number 4 is special because it has proper divisors 1 and 2.
- The number 6 is not special because it has proper divisors 1, 2, and 3.
Return the count of numbers in the range [l, r] that are not special.
Example 1:
Input: l = 5, r = 7
Output: 3
Explanation:
There are no special numbers in the range [5, 7].
Example 2:
Input: l = 4, r = 16
Output: 11
Explanation:
The special numbers in the range [4, 16] are 4 and 9.
Constraints:
1 <= l <= r <= 10^9
Solution
Approach: Sieve of Eratosthenes
A number is special exactly when it is the square of a prime. Sieve the primes up to 31623 (just above the square root of 10^9). The special numbers in [l, r] are the squares of primes in [ceil(sqrt(l)), floor(sqrt(r))]; count them as cnt and return r - l + 1 - cnt.
Complexity: O(sqrt(m)) time and space, where m = 10^9.
from math import ceil, floor, sqrt
m = 31623
primes = [True] * (m + 1)
primes[0] = primes[1] = False
for i in range(2, m + 1):
if primes[i]:
for j in range(i + i, m + 1, i):
primes[j] = False
class Solution:
def nonSpecialCount(self, l: int, r: int) -> int:
lo = ceil(sqrt(l))
hi = floor(sqrt(r))
cnt = sum(primes[i] for i in range(lo, hi + 1))
return r - l + 1 - cnt