Solved Problem - Factorization
Explore how to count the number of factors of a given number efficiently by applying mathematical insights that reduce complexity from linear to square root time. Understand factor pairs and optimization strategies that enable faster computation for large values, preparing you for more advanced number theory problems.
We'll cover the following...
Problem statement
Given a number , count the number of factors of the number N.
Input format
A single line of input contains the number .
Output format
Print a single integer equal to the number of factors of .
Sample
Input
36
Output
9
Explanation
Factors of
Count:
Brute force
The brute force solution would be to loop over all the numbers from 1 to N and check if it is a factor. If it is, you would then print it.
We can use the modulus operator to check if it’s a factor or not.
Here is the code:
Since there is only one loop that runs N times, the runtime complexity is simply .
This is good enough for up to or even , but it will not work with the given constraints. Typically, you have 1-3 seconds for the code to execute and print the results.
Let’s see how we can optimize it further.
Optimization
Let’s take a number, n, and one of its factors, a. Then there must be another factor, b, such that
or
Also, let’s assume
Which means if we find two factors, a and b of n such that ab=n, one is always less than or equal to and the other one is greater than or equal to .
Factors always come in pairs, except when the number is a perfect square. In which case both factors are equal.
Based on this observation, we only need to iterate up to times. The complexity is reduced to .
Below is the optimized code for the above problem.
In the next lesson, we’ll see how we can use the same observation to speed up the primality test. The primality test determines whether the input is prime or not.