The Square Root Shortcut
The Square Root Shortcut

The Square Root Shortcut: Coding Smarter, Not Harder

If you've ever written a script to find prime numbers, you've probably used a loop to check for divisors. But are you checking too many?

When I first started out, I'd check every number from 2 all the way up to my target. It works, but it's slow. There is a beautiful mathematical shortcut that can make your code significantly faster: The Square Root Rule.

The Logic of Factor Pairs

The secret is that factors never travel alone--they always come in pairs. Think of the number 100. Its square root is 10. If you list the pairs that multiply to 100, look at how they behave:

  • 2 x 50 = 100
  • 4 x 25 = 100
  • 5 x 20 = 100
  • 10 x 10 = 100 (The "Tipping Point")

Notice the pattern? In every pair, one number is always less than or equal to 10, and the other is greater than or equal to 10.

Why This Saves Your CPU

If you are checking if 100 is prime (spoiler: it's not), and you have already tested every number up to 10 without finding a divisor, you can stop right there.

Why? Because if there were a larger factor (like 20), its "partner" (5) would have been found earlier in your search. If you didn't find the small partner, the large one can't exist!

The Code Difference

In JavaScript, instead of writing a loop like this:

for (let i = 2; i < num; i++)

You can write it like this:

for (let i = 2; i <= Math.sqrt(num); i++)

The result? If you are checking if 1,000,001 is prime, you only have to run 1,000 iterations instead of 1,000,000. That is a 1,000x speed increase just by understanding a simple property of multiplication.

Moral of the story: Sometimes the best way to optimize your code isn't a better server--it's a bit of middle-school math.