Nine Divisors
JavaView on GFG
Advertisement
Intuition
Count numbers up to n that have exactly 9 divisors. Numbers of form p^8 or p^2*q^2.
Algorithm
- 1Sieve primes up to sqrt(n). Count: p^8 <= n gives one form. p^2*q^2 <= n where p!=q gives another. Combine.
Common Pitfalls
- •Exactly 9 divisors: n=p^8 (divisors 1,p,...,p^8) or n=p^2*q^2 (divisors: 3*3=9). Use sieve.
Nine Divisors.java
Java
// Approach: Count numbers up to n with exactly 9 divisors: form p^8 or p^2*q^2 (distinct primes).
// Time: O(sqrt(n) * log log n) Space: O(sqrt(n))
class Solution {
public static int countNumbers(int n) {
int ans = 0;
for (int i = 6; i * i <= n; i++) {
int x = i * i, cnt = 1;
for (int j = 2; j * j < x; j++) {
if (x % j == 0)
cnt++;
if (cnt > 4)
break;
}
if (cnt == 4)
ans++;
}
return ans;
}
}Advertisement
Was this solution helpful?