Only prime powers contribute to the factor-count multiplicatively. Finding exponents ei for each prime pi and computing the product (ei+1) yields the answer.
classSolution {
public:longlong countDivisors(longlong n) {
if (n <=1) return1;
longlong ans =1;
for (longlong p =2; p * p <= n; ++p) {
if (n % p !=0) continue;
int cnt =0;
while (n % p ==0) { n /= p; ++cnt; }
ans *= (cnt +1);
}
if (n >1) ans *=2;
return ans;
}
};
classSolution {
publiclongcountDivisors(long n) {
if (n <= 1) return 1;
long ans = 1;
for (long p = 2; p * p <= n; ++p) {
if (n % p != 0) continue;
int cnt = 0;
while (n % p == 0) { n /= p; ++cnt; }
ans *= (cnt + 1);
}
if (n > 1) ans *= 2;
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
funcountDivisors(nInput: Long): Long {
var n = nInput
if (n <=1) return1var ans = 1Lvar p = 2Lwhile (p * p <= n) {
if (n % p !=0L) { p++ ; continue }
var cnt = 0Lwhile (n % p ==0L) { n /= p; cnt++ }
ans *= (cnt + 1)
p++ }
if (n > 1) ans *=2return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution:
defcount_divisors(self, n: int) -> int:
if n <=1:
return1 ans =1 p =2while p * p <= n:
if n % p !=0:
p +=1continue cnt =0while n % p ==0:
n //= p
cnt +=1 ans *= (cnt +1)
if n >1:
ans *=2return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
pubstructSolution;
impl Solution {
pubfncount_divisors(mut n: u64) -> u64 {
if n <=1 { return1 }
letmut ans =1u64;
letmut p =2u64;
while p * p <= n {
if n % p !=0 { p +=1; continue }
letmut cnt =0u64;
while n % p ==0 { n /= p; cnt +=1 }
ans *= cnt +1;
p +=1;
}
if n >1 { ans *=2 }
ans
}
}
⏰ Time complexity: O(sqrt(n)) in the worst case (trial division up to sqrt(n)), more precisely O(pi(sqrt(n))) if using primes, where pi(x) is number of primes ≤ x. For typical inputs this is fast for 64-bit n.
🧺 Space complexity: O(1) extra memory (just counters and a few variables).
Every divisor d <= sqrt(n) pairs with n/d. Counting divisors by scanning d from 1 to floor(sqrt(n)) and incrementing by 2 when d divides n (or by 1 when d*d == n) gives the count without factorization.
classSolution:
defcount_divisors_sqrt(self, n: int) -> int:
if n <=0: return0 cnt =0 d =1while d * d <= n:
if n % d ==0:
cnt +=1if d * d == n else2 d +=1return cnt