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:
- Find all prime factors of the given number through this solution.
- Get all possible combinations of those prime factors.
However, it doesn't seem to be a good one.
Best Answer
Factors are paired.
1
and24
,2
and12
,3
and8
,4
and6
.An improvement of your algorithm could be to iterate to the square root of
num
instead of all the way tonum
, and then calculate the paired factors usingnum / i
.