What is the fastest way in Java to get the amount of factors a number has
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
If you need the number of positive divisors of an integer in Java, the fastest practical exact method for one value is based on prime factorization. A naive loop from 1 to n works, but it wastes effort because divisor pairs make most checks unnecessary.
For single numbers, the best pattern is factorization plus the divisor-count formula. For many numbers in a range, you would switch to a sieve-based approach instead.
The Naive Method
This basic version is correct:
But it is O(n), which becomes slow for large inputs.
A Better Start: Scan to the Square Root
Divisors come in pairs. If i divides n, then n / i also divides n. That means you only need to test up to sqrt(n):
This is already much faster than checking every number up to n.
The Prime Factorization Formula
If
n = p1^a1 * p2^a2 * ... * pk^ak
then the number of positive divisors is:
(a1 + 1) * (a2 + 1) * ... * (ak + 1)
So once you know the prime exponents, the divisor count is immediate.
Java Implementation
Example:
For 36, the factorization is 2^2 * 3^2, so the answer is (2 + 1) * (2 + 1) = 9.
Why This Is Fast
The loop only tests candidate factors up to the square root of the shrinking remaining value. That makes it efficient for one exact query and far better than scanning all integers up to n.
It also counts divisors mathematically instead of enumerating them one by one. That is why the factorization version is the usual exact answer when the question is about speed for a single number.
When Many Queries Change the Answer
If you need divisor counts for many numbers up to a limit, repeated trial division stops being ideal. In that case, a sieve or smallest-prime-factor table is often faster overall because you precompute once and answer many queries cheaply.
So the practical rule is:
- one number: factorization method
- many numbers in a range: sieve-based method
That difference matters in competitive programming and number-theory utilities.
Common Pitfalls
- Looping all the way to
nwhen a square-root bound is enough. - Forgetting that perfect squares contribute only one divisor at the square root in the pair-count method.
- Using
intwhen the input range should really belong. - Ignoring the divisor-count formula after the number has already been factored.
- Forgetting to reject zero or negative inputs for a positive-divisor function.
Summary
- The naive divisor-count loop is correct but unnecessarily slow.
- A square-root scan is a solid optimization for one number.
- The best exact general method for one value is prime factorization plus the divisor-count formula.
- For many queries across a range, use a sieve-based strategy instead.
- Choose the algorithm based on workload, not just on code brevity.

