√τom
2011-01-26 10:28:10 UTC
I'll leave the details of the problem out of this question, as I don't have trouble with those. Here is my method for finding factors (both prime and composite) of a given number:
public static int countFactors(long n)
{
int count = 0;
for (long i = 1; i <= n; i++)
{
if (n % i == 0)
count++;
}
return count;
}
For example, for n = 28, countFactors(28) will return 6, because the factors of 28 are {1, 2, 4, 7, 14, 28}.
This works fine for smaller numbers, but in my case I need to scan hundreds of thousands of numbers bigger than 200,000,000,000 (which is why I'm using longs). I think I understand the problem: I'm scanning every number from 1->n, which for large values is a very big amount of numbers to scan. This makes my program run significantly slower. How can I modify countFactors() to be more efficient?