unsigned int* factor(unsigned int n)
If unsigned int is a typical 32-bit type, the numbers are too small for any of the more advanced algorithms to pay off. Of course, the usual improvements for trial division.
If you move the division by 2 from the loop and divide only into the odd numbers in the loop, like those mentioned by Pete Becker , you are essentially halving the number of divisions needed to determine the input number, and thus speed up the function by almost 2 times.
If you take this step further, and also eliminate multiples of 3 from the divisors in the cycle, you will reduce the number of divisions and, therefore, increase the speed by a factor close to 3 (on average, most numbers do not have large large coefficients, but are divisible by 2 or by 3, but for those who accelerate much less, but these numbers change quickly. If you define a longer range of numbers, most of the time is spent factoring several numbers with large prime divisors).
// if your compiler doesn't transform that to bit-operations, do it yourself while(n % 2 == 0) { tab[dim++] = 2; n /= 2; } while(n % 3 == 0) { tab[dim++] = 3; n /= 3; } for(int d = 5, s = 2; d*d <= n; d += s, s = 6-s) { while(n % d == 0) { tab[dim++] = d; n /= d; } }
If you often call this function, it would be advisable to precompute 6542 primes not exceeding 65535, store them in a static array and divide only by primes in order to exclude all divisions, which are a priori guaranteed not to find a divisor.
If unsigned int is more than 32 bits, then using one of the more advanced algorithms would be beneficial. You should start with trial divisions to find small simple factors (do you need a small value <= 1000 , <= 10000 , <= 100000 or maybe <= 1000000 , my gut feeling says that one of the smaller values โโis better on average ) If the factorization is not completed after the trial separation phase, check whether the remaining coefficient is simple, for example, a deterministic (for the range in question) version of the Miller-Rabin test. If not, find the odds using your favorite advanced algorithm. For 64-bit numbers, I would recommend the Pollard rho algorithm or factorization of elliptic curves. The Pollard rho algorithm is easier to implement, and for numbers of this magnitude, factors are found in the nearest comparable factors, so my first recommendation.