What an odd limit; 2147483742 = 2 ^ 31 + 94.
As others have pointed out, for a number this is a small trial division into prime numbers, most likely quite quickly. Only if this is not the case, you can try the Pollard Roe method:
long rho(n, c) { long t = 2; long h = 2; long d = 1; while (d == 1) { t = (t*t + c) % n; h = (h*h + c) % n; h = (h*h + c) % n; d = gcd(th, n); } if (d == n) return rho(n, c+1); return d; }
Called as rho(n,1) , this function returns a (possibly compound) coefficient n; put it in a loop and name it again if you want to find all factors n. You will also need validation; for your limit, the Rabin-Miller test with bases 2, 7 and 61 proved its accuracy and reasonableness. You can learn more about programming with primes in my blog .
But in any case, given such a small limit, I think that you are better off using trial division by primes. Everything else can be asymptotically faster, but almost slower.
EDIT: This answer received a few recent posts, so I am adding a simple program that factorizes wheels with 2,3,5-wheels. Called as wheel(n) , this program prints the coefficients n in ascending order.
long wheel(long n) { long ws[] = {1,2,2,4,2,4,2,4,6,2,6}; long f = 2; int w = 0; while (f * f <= n) { if (n % f == 0) { printf("%ld\n", f); n /= f; } else { f += ws[w]; w = (w == 10) ? 3 : (w+1); } } printf("%ld\n", n); return 0; }
I discuss wheel factorization on my blog ; the explanation is long, so I will not repeat it here. For integers that match in long , it is unlikely that you can significantly improve the wheel function mentioned above.