The first thing to notice is to find all the prime factors. Once you have this, it's easy to find the number of total divisors: for each number, add 1 to the number of times it appears, and multiply them together. So for 12 = 2 * 2 * 3 you have (2 + 1) * (1 + 1) = 3 * 2 = 6 factors.
The following follows from the first: when you find a factor, divide it so that the resulting number is less. When you combine this with the fact that you only need to check the square root of the current number, this is a huge improvement. For example, consider N = 10714293844487412. It would be naive to take N steps. Checking to the square root takes sqrt (N) or about 100 million steps. But since factors 2, 2, 3, and 953 were discovered at an early stage, you really only need to check one million - a 100-fold improvement!
Another improvement: you do not need to check each number to find out if it divides your number, just prime numbers. If it is more convenient, you can use 2 and odd numbers, or 2, 3, and the numbers 6n-1 and 6n + 1 (base wheel).
Here is another nice improvement. If you can quickly determine if a number is prime, you can reduce the need for separation even further. Suppose that after removing small factors, you have 120528291333090808192969. Even checking to the square root will take a lot of time - 300 billion steps. But the Miller-Rabin test (very fast - perhaps 10 to 20 nanoseconds) will show that this number is composite. How does this help? This means that if you check your cube root and find no factors, then there will be exactly two prime numbers. If the number is a square, its coefficients are primary; if the number is not a square, the numbers are different strokes. This means that you can multiply your "total" by 3 or 4, respectively, to get the final answer - without even knowing the factors! This may be more important than you expected: the number of necessary steps is reduced from 300 to 50 million, 6000 times more!
The only problem with the above is that Miller-Rabin can only prove that numbers are compound; if he set the prime, he cannot prove that the number is prime. In this case, you might want to write a strength test function to save yourself the trouble of multiplying by the square root of a number. (Alternatively, you could just do a few more Miller-Rabin tests if you were satisfied with high confidence that your answer is correct, and not proof that it is. If the number passes 15 tests, then it is made up with probability less than 1 in a billion.)
Charles
source share