This is actually a problem for which no good solution is known. For this reason, RSA encryption actually depends on the computational difficulty of factoring numbers. See: Integer Factorization
However, you may be able to speed up the algorithms already given by only looking at numbers up to the square root of n, and checking if they are factors by checking if n % i == 0. If this is true, you can find the corresponding factor greater than n^(.5) by taking n / i.