![]() |
VOOZH | about |
Given a number n, print count of numbers in the range from 1 to n having exactly3 divisors.
Examples:
Input: n = 16
Output: 2
Explanation: Only 4 and 9 have exactly three divisors.Input: n = 100
Output: 4
Explanation: 4, 9, 25 and 49 have exactly three divisors.
Table of Content
For each number, it counts how many divisors it has by checking all possible divisors from 1 to that number. If a number has exactly 3 divisors, it is printed
4
The number having exactly 3 divisors must be a perfect square of a prime number.
For this to happen, the number must be the square of a prime.
If p is a prime number, then the divisors of p2 (the square of p) will be:
1 (as it's divisible by 1)
p (as it is divisible by p)
p2 (as it is divisible by itself)
Therefore, the only way for a number to have exactly 3 divisors is if it is the square of a prime number. This is because, for any non-square number, there are more than 3 divisors, and for a perfect square of a non-prime number, it would have more than 3 divisors as well. Thus, the number must be the square of a prime, and that's why we specifically look at perfect squares of primes.
4
Time Complexity: O(n*log(log(n)))
Auxiliary Space: O(n)
In this method, we iterate through all numbers up to sqrt(n) and check if each is prime. If a number is prime, its square will have exactly three divisors (1, the prime itself, and its square). We count such primes whose squares are ≤ n. This approach avoids using extra space like a sieve, but has a time complexity of approximately O(n^(3/4)), because we perform a primality check (which takes up to O(√i) time) for each number up to √n.
Run a loop from 2 to sqrt(n) and check if the current element is prime or not, if it is so then print that number, but this method will increase the time complexity of the solution
Step for implementation:
4
Time Complexity: O(n3/4) because we call isPrime √n times, and for each i, isPrime(i) takes O(√i) time. Therefore, total time is the sum √1 + √2 + ... + √√n, which integrates to O(n3/4)
Auxiliary Space: O(1)