dumbass's blog

By dumbass, history, 3 years ago, In English,

Link to PDF (Latex Formatted)

Topic : Counting Divisors of a Number

Pre Requisites : Basic Maths , Factorisation , Primality testing

Motivation Problem :

There are T test cases. Each test case contains a number N. For each test case , output the number of factors of N.

1 <  = T <  = 10

1 <  = N <  = 1018

Note : 1 and N are also treated as factors of the number N.

Solution :

Naive Solution Factorisation

The most naive solution here is to do the factorisation. But as we can see, it will surely receive the Time Limit Exceeded verdict. You may try to compute the prime numbers till required range and loop over them , but that too exceeds the usual limit of 108 operations. Some optimisations and heuristics may allow you to squeeze through your solution, but usually at the cost of a few TLE's.

Supposing you fit in the above description and cannot think of anything better than the naive solution, I would like to present to you a very simple algorithm which helps you count the number of divisors in , which would be useful for this kind of questions. This algorithm only gives us the count of factors, and not the factors itself.

Firstly, let's do a quick recap of how we obtain the algorithm for any number N :

We write N as product of two numbers P and Q.

Looping over all values of P gives us the count of factors of N.

Before you move forward to the next section, it would be useful if you try to come up with an algorithm that finds the count of factors in . As a hint, the way of thinking is same as that of getting to the algorithm.

Counting factors in

Let's start off with some maths to reduce our factorisation to for counting factors :

We write N as product of three numbers P, Q and R.

We can loop over all prime numbers in range and try to reduce N to it's prime factorisation, which would help us count the number of factors of N.

To know how to calculate divisors using prime factorisation, click here.

We will split our number N into two numbers X and Y such that X * Y = N. Further, X contains only prime factors in range and Y deals with higher prime factors (). Thus, gcd(X , Y) = 1. Let the count of divisors of a number N be denoted by the function F(N). It is easy to prove that this function is multiplicative in nature, i.e., F(m * n) = F(m) * F(n), if gcd(M,N) = 1. So, if we can find F(X) and F(Y), we can also find F(X * Y) or F(N) which is the required quantity.

For finding F(X), we use the naive trial division to prime factorise X and calculate the number of factors. Once this is done, we have Y = N / X remaining to be factorised. This may look tough, but we can see that there are only three cases which will cover all possibilities of Y :

  1. is a prime number : F(Y) = 2.
  2. is square of a prime number : F(Y) = 3.
  3. is product of two distinct prime numbers : F(Y) = 4.

We have only these three cases since there can be at max two prime factors of Y. If it would have had more than two prime factors, one of them would surely have been , and hence it would be included in X and not in Y.

So once we are done with finding F(X) and F(Y), we are also done with finding F(X * Y) or F(N).

Pseudo Code :

N = input()
primes = array containing primes till 10^6
ans = 1
for all p in primes :
            if p*p*p > N:
                  break
            count = 1
            while N divisible by p:
                  N = N/p
                  count = count + 1
            ans = ans * count
if N is prime:
            ans = ans * 2
else if N is square of a prime:
            ans = ans * 3
else if N != 1:
            ans = ans * 4

Checking for primality can be done quickly using Miller Rabin. Thus, the time complexity is for every test case and hence we can solve our problem efficiently.

At this point, you may think that in a similar way, we can reduce this to by handling some cases. I have not thought much on it, but the number of cases to be handled are high since after trial division N could be factorised into one, two or three primes. This is easy enough to code in contest environment, which is our prime objective.

This trick is not quite commonly known and people tend to make bugs in handling the three cases. A problem in regionals which uses this trick directly :

Problem F | Codeforces Gym

You can try also this technique on problems requiring factorisation for practice purposes.

Hope you found this useful! Please suggest more problems to be added as well as any edits, if required.

Happy Coding!

 
 
 
 
  • Vote: I like it  
  • +172
  • Vote: I do not like it  

»
3 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Good one :) (Y)

»
3 years ago, # |
  Vote: I like it +8 Vote: I do not like it

You can't really call this " factorization" though, you only get the exponents, not the factors.

  • »
    »
    3 years ago, # ^ |
    Rev. 2   Vote: I like it +9 Vote: I do not like it

    Agreed, that's why I put the title as "Counting Divisors". For the sub heading, I couldn't think of anything short and simple, so I went ahead with that. What could it be changed to?

    Edit : I edited the post so that it isn't misleading anymore!

»
3 years ago, # |
Rev. 5   Vote: I like it 0 Vote: I do not like it

No wait I missed some cases, ignore :P

  • »
    »
    3 years ago, # ^ |
      Vote: I like it +3 Vote: I do not like it

    isnt right, take 101 * 101 * 97 as an example, you just loop till 40!

»
3 years ago, # |
  Vote: I like it +5 Vote: I do not like it

Auto comment: topic has been updated by himanshujaju (previous revision, new revision, compare).

»
3 years ago, # |
  Vote: I like it -13 Vote: I do not like it

To check if N is prime or not at the end of your algorithm you have to use O(sqrt(n)) algorithm...

  • »
    »
    3 years ago, # ^ |
      Vote: I like it +11 Vote: I do not like it

    Read up on Miller Rabin, I mentioned that explicitly in the post.

»
3 years ago, # |
  Vote: I like it 0 Vote: I do not like it

You mentioned the following part -- We have only these three cases since there can be at max two prime factors of Y. If it would have had more than two prime factors, one of them would surely have been , and hence it would be included in X and not in Y.

Could you please explain this part a bit in detail. I am still now sure about why there can be at max two prime factors for Y and not 3 or more.

  • »
    »
    3 years ago, # ^ |
      Vote: I like it +3 Vote: I do not like it

    Suppose N has 3 primes factors left after the trial division is done. So, N = p1 * p2 * p3.

    Now , p1 , p2 and p3 all have to be greater than or else they would have been found in the trial division. Their product will be greater than N , which is not possible and hence we contradict what we started with.

    Try a few examples in pen and paper and read this proof again in case you still don't understand. Don't hesitate to reply for any clarifications.

»
3 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

What is a good way for checking whether a given number is a square?

I'm using this:

bool is_square(ll n) {
	ll sqr = sqrt(n);
	return sqr * sqr == n;
}
»
3 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Someone please provide code for Miller-Rabin primality test. Thanks!

»
3 years ago, # |
Rev. 3   Vote: I like it +3 Vote: I do not like it

I tried solving the problem using Miller-Rabin as you said. The thing is: when we are limited to ~ 64 bits, doing an exponentiation a^d (mod n) may give overflow. This happens because, if n is too large (like 10^18), the value of a^d will overflow before we can apply the modulus operator (applying it when it is less than n won't help). Is there any way to overcome this or do we need to work with bigger types?

  • »
    »
    3 years ago, # ^ |
      Vote: I like it +6 Vote: I do not like it

    I use this to avoid overflow (taken from topcoder tutorial on primality) :

    /* this function calculates (a*b)%c taking into account that a*b might overflow */
    long long mulmod(long long a,long long b,long long c){
        long long x = 0,y=a%c;
        while(b > 0){
            if(b%2 == 1){
                x = (x+y)%c;
            }
            y = (y*2)%c;
            b /= 2;
        }
        return x%c;
    }
    
    • »
      »
      »
      3 years ago, # ^ |
        Vote: I like it +10 Vote: I do not like it

      2015:


      #define LL long long LL mulmod(LL a, LL b, LL c) { return (__int128)a * b % c }

      `

      • »
        »
        »
        »
        3 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        __int128 is a non-standart GCC extension. For example, Microsoft has no plans to implement it in MSVC

»
3 years ago, # |
  Vote: I like it 0 Vote: I do not like it

can u provide links to some spoj problem that uses this technique?

  • »
    »
    3 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Unfortunately, I know only one question yet. You can use this on any question where logic for counting factors also passes. Havnt been solving on SPOJ recently, so no idea.

»
3 years ago, # |
  Vote: I like it +17 Vote: I do not like it

The Pollard-rho algorithm can give the factorization of n in O(n1 / 4) time.

»
2 years ago, # |
  Vote: I like it 0 Vote: I do not like it

When Y consist of two prime or Y is a prime how can i check it. Thanks in Advance.

  • »
    »
    2 years ago, # ^ |
      Vote: I like it +4 Vote: I do not like it

    suppose Y<=10^18.

    iterate over all primes from 2 to 10^6 and keep dividing Y by them meanwhile keep a count of factors.

    After this step either you have found the solution or the Y left contains prime factors > 10^6 .

    NOTE : now notice that Y cant have more than two prime factors at this step because factors left are already greater than 10^6 .

    • case 1: Y is prime , using miller rabin test check it .
    • else case 2 : Y has two prime factors and both of them are >= 10^6 .
»
2 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Am I allowed to translate it to Chinese with your name on it?

  • »
    »
    2 years ago, # ^ |
      Vote: I like it +2 Vote: I do not like it

    Sure! With/without name doesn't matter much :)

»
21 month(s) ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

please can you explain why F(y) ={ 2 , 3 , 4 } in the three cases !! I understand why we have only three cases but I can't understand who we get F(y) value .. thanks in advance

  • »
    »
    21 month(s) ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    If y is a prime it will have 2 divisors: 1 and y itself. If y is a square of a prime it will have 3 divisors: 1, sqrt(y) and y itself. If y is a product of two distinct primes(suppose p1, p2) it will have 4 divisors: 1, p1, p2 and y itself which is equal to p1*p2. I think you forgot to check the link mentioned in the post about counting divisors using prime factorization.

»
19 months ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

Can someone please let me know how we are maintaining the array of primes for a very large number like 10^18 for this? Is it possible to return the count for factors of a dataset extended to 10^18?

»
18 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Can you please share your accepted code for the above Problem.

»
15 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Can someone elaborate on how we can check if Y is any of the three cases? I can't see this through!

  • »
    »
    15 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Check if Y is a prime number by using Miller Rabin test.
    If it fails, check if the sqrt of Y is prime by using the same test.
    If that fails too, then the number must belong to the third case.

»
12 months ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

ok. suppose, we want to check nod of a prime number and this number is n>10^6; so,in your pseudo code, the number failed to go through in 1st while loop; after it comes [ if N is prime ] this condition. but we stored prime only up to 10^6. since the number can't go through while loop and the value of the number (n) cannot be changed, how I check the number is prime or not???? how it passes this [ if N is prime ] condition???

Example, if a number is 50761746622, what is it's output??

  • »
    »
    12 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    If p*p*p then break. Since p is up to 10^6 then p*p*p is up to 10^18. Your big number is smaller than 10^18. So the cycle will break at some moment. Since your number is divisible by two it is either of form 2*some_prime or of form 2*product_of_some_primes. If first case then N is divided by two and after that cycle breaks and we check N/2 for primality. If case two than some primes my be eliminated before cycle breaks. Strictly speaking, only primes not greater than the cubic root will be eliminated. And we would end up with your number reduced to two possible the same primes.

  • »
    »
    12 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    You don't use the sieve to check if the result is prime. You use Rabin-miller probabilistic primality testing to check if it is prime. Look up "Rabin-Miller" and go to wikipedia to read about it. It is a way to check with high probability that a number is prime or not.

»
9 months ago, # |
  Vote: I like it 0 Vote: I do not like it

If N is a prime number greater than 1e17 then Y=N. So, how to check whether Y is prime or Y is a square of prime or Y is product of two prime? (Initially it is not known that N is prime greater than 1e17)

»
3 months ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

Great algorithm! :-) Miller-Rabin's primality test and Fermat's primality test were some new algorithms I came to know!