In J, how can I find the extended precision integer floor square root
I understand that when I take the square root ( %:
) of a number that does not result in an integer, my answer is a float. I'm looking to find the floor ( <.
) of a square root to get an integer result. Does J have a built-in way to achieve this? Do I need to loop over to find the answer?
Dropping in multiple queries with extended precision ( x:
) certainly doesn't do this.
rootanddiffa =: 3 : '(y - root ^ 2);(root =. <. %: y)'
rootanddiffa 24
βββ¬ββ
β8β4β
βββ΄ββ
rootanddiffa 26
βββ¬ββ
β1β5β
βββ΄ββ
rootanddiffa 99999999999999x
ββββ¬βββββββββ
β_1β10000000β
ββββ΄βββββββββ
rootanddiffb =: 3 : '(y - root ^ 2);(root =. x: <. x: %: y)'
rootanddiffb 24
βββ¬ββ
β8β4β
βββ΄ββ
rootanddiffb 99999999999999x
ββββ¬βββββββββ
β_1β10000000β
ββββ΄βββββββββ
source to share
From "J for C: 32 Programmers" :
The key is idiom <. @v (or>. @v), where v is the verb you want to apply. When you code <. @V, the interpreter knows that you are only interested in the integer part of the result, and if the operand is an exact precision, the interpreter will accurately evaluate the whole part of the result.
So, you have to use <.@%:
:
rt2 =: 3 :'(y - root ^ 2);(root =. <.@%: y)' rt2 99999999999999x ββββββββββ¬ββββββββ β19999998β9999999β ββββββββββ΄ββββββββ
See also Vocabulary - Extended and Rational Arithmetic
<. @f and>. @f produces widened integer results when applied to widened integer arguments.
source to share
It works:
sqrt=: <.@%:
sqrt 99999999999999x
For more information see http://www.jsoftware.com/help/jforc/elementary_mathematics_in_j.htm
source to share