How can I make this code faster?

a and b are divisors of n if a * b = n. You can, without loss of generality, set b >= a. Therefore a * a is the upper limit; i.e. you only need to consider up to and including the square root of n. Once you have an a, you can trivially infer b.

You can set the upper limit to be d * d <= n rather than d <= sqrt(n) so obviating any computation of a square root. That will be marginally faster still.

Browse More Popular Posts

Leave a Comment