Does anyone know an algorithm for getting square roots of positive integers? The Math Commands osax is not available for OS X and the shell cannot calculate sqr without additional software like “octave”. - I found Maple code on Wikipedia.org but am stuck with the line

intsqrt(9)
on intsqrt(z)
local A, B, _a, _b, c, e, r
set A to 1
set B to z
set e to z - 1
repeat while e > 1
set r to random number from A + 1 to B - 1
-- This has not been translated correctly
set _a to r -- A :=r(e)
if _a > A and _a ^ 2 < z then
set A to _a
end if
if _a < B and _a ^ 2 > z then
set B to _a
end if
set e to B - A
end repeat
return A
end intsqrt

Any idea how to translate this line?

TIA!
Thomas

Model: Mac-Mini
Browser: Firefox 1.5.0.3
Operating System: Mac OS X (10.4)

This was what I was looking for but did not find… hitting “sqr” and pressing “tab” in the terminal did not bring “sqrt” up. Where did you get to know about it from?

That’s absolutely correct! I extended it to intsqrt(aNumber) because I needed the integer part only for calculating primes.

on intsqrt(aNumber)
set aNumber to aNumber ^ 0.5
try
set aNumber to ((characters 1 thru (offset of "," in (aNumber as string)) of (aNumber as string)) as string) as integer
end try
log aNumber
end intsqrt

Besides the rounding up that you mention, there are a couple of other points to bear in mind when comparing as integer with div, Adam:

¢ as just mentioned [url=http://bbs.applescript.net/viewtopic.php?pid=60363#p60363]here[/url], the real-to-integer coercion was only introduced in AppleScript 1.9.2/Mac OS X 10.3
¢ the div function is somewhat faster than the coercion (by a factor of about x3, here)

Thanks for the test info Kai - I had thought that coercion would be faster without actually testing it. I wonder why Satimage puts “floor” in their mathematical operators given that div 1 produces the same result, and “round realnum rounding down” must be a real dog.

I’d guess that the rounding down parameter was included with the round function purely for completeness. Again, when comparing native AppleScript with an external call (particularly for relatively trivial operations), there’s really no contest. In this case, div is at least 12 times faster than rounding down.