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β”‚
β””β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”˜

      

+3


source to share


2 answers


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.

+4


source


It works:

sqrt=: <.@%:
sqrt 99999999999999x

      



For more information see http://www.jsoftware.com/help/jforc/elementary_mathematics_in_j.htm

+2


source







All Articles