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 the square root in order to get an integer result. Does J have a built-in way to achieve this? Do I need to resort to a loop to find my answer?
Tossing in a few extended precision (x:
) requests certainly doesn't do it.
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│
└──┴────────┘
From "J for C Programmers: 32":
The key is the idiom <.@v (or >.@v), where v is the verb you want to apply. When you code <.@v, the interpreter knows you are interested in only the integer part of the result, and if the operand is exact-precision, the interpreter will evaluate the integer part of the result exactly.
So, you have to use <.@%:
:
rt2 =: 3 :'(y - root ^ 2);(root =. <.@%: y)'
rt2 99999999999999x
┌────────┬───────┐
│19999998│9999999│
└────────┴───────┘
See also Dictionary - Extended and Rational Arithmetic
<.@f and >.@f produce extended integer results when applied to extended integer arguments.