Neither is the most efficient. The square of any number \$x\$ is
\$(x-1)**2 +(x-1) + x\$
Or in English instead of math, the square of any number is equal to the number less than it squared + the number less than it + the number itself. eg: 5 squared = 4 squared (16) + 4 (subtotal 20) + 5 (total = 25). This is true for all positive whole numbers.
So, for example, you're squaring a million: you'd have to add a million to itself a million times, but using as many loops, my routine was finding the square of 1, 2, 3...1,000,000. So the processor only has to handle a number as large as a million once, instead of a million times.
When I was in Intro to Computer Science in 1978 I wrote a Basic routine like this (where X
is the number to be squared, L
is loop counter and S
is the resulting square, all defined as integers):
DEF X, L, S as Int
S=0
for L = 1 to X
S=S+L-1+L
Next
? "The square of",X," equals",S
Back in the fall of 1977 when this was written, the Mainframe at my college had a 4-bit processor (which could operate on numbers between 0 and 15 without storing and carrying). I had the program grab the time, square the numbers 1 to 100 using the computer's intrinsic square function and grab the time again, subtracting the starting time from the ending time to see how long the computer took to square the 1st 100 numbers in machine language. I grabbed times on either side of the routine running my formula on the same 100 numbers. It was .02 seconds faster to run my higher language routine than the computer's built in square function.
The school, auditing computer use by the various classes, noticed my program and called me in to meet the fellow with the doctorate running the department. They were amazed that a 1st year programmer was proving mathematical theory instead of fighting his way through the idea of programming. Researched it and published a paper at the ensuing mathematical conference. Within a year, it (and its associated programs for squaring negative, fractional and mixed numbers were adopted in machine language as ROM for the square function by 3 of the 4 largest mainframe manufacturers. The year in review for technology's computer expert said it would save heavy computer users (colleges, military, engineering firms) $3.56B in CPU time per year.
hope that helps.