Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently getting all divisors of a given number

According to this post, we can get all divisors of a number through the following codes.

for (int i = 1; i <= num; ++i){     if (num % i == 0)         cout << i << endl; } 

For example, the divisors of number 24 are 1 2 3 4 6 8 12 24.

After searching some related posts, I did not find any good solutions. Is there any efficient way to accomplish this?

My solution:

  1. Find all prime factors of the given number through this solution.
  2. Get all possible combinations of those prime factors.

However, it doesn't seem to be a good one.

like image 301
zangw Avatar asked Nov 05 '14 09:11

zangw


People also ask

What is the fastest way to find divisors of a number?

The formula for calculating the total number of divisor of a number ′n′ where n can be represent as powers of prime numbers is shown as. If N=paqbrc . Then total number of divisors =(a+1)(b+1)(c+1).

How do you find the number of divisors efficiently?

Once you have the prime factorization, there is a way to find the number of divisors. Add one to each of the exponents on each individual factor and then multiply the exponents together. Save this answer.

What is the formula for divisors of a number?

What is the formula to find a divisor? If the remainder is 0, then Divisor = Dividend ÷ Quotient. If the remainder is not 0, then Divisor = (Dividend – Remainder) /Quotient.


1 Answers

Factors are paired. 1 and 24, 2 and 12, 3 and 8, 4 and 6.

An improvement of your algorithm could be to iterate to the square root of num instead of all the way to num, and then calculate the paired factors using num / i.

like image 146
Yu Hao Avatar answered Oct 01 '22 02:10

Yu Hao