3

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│
└──┴────────┘
Dane
  • 1,201
  • 8
  • 17

2 Answers2

4

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.

Eelvex
  • 8,975
  • 26
  • 42
  • 1
    There's enough wisdom behind J that I just knew there had to be a way to do this. – Dane May 14 '15 at 19:32
2

This appears to work:

sqrt=: <.@%:
sqrt 99999999999999x

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

Aky
  • 1,777
  • 1
  • 14
  • 19