Number of values between input and next highest square

Brain-Flak, 38, 22 bytes

{([[]](({})))}{}([]<>)

Try it online!

I'm very proud of this answer. IMO, one of my best brain-flak golfs.

How does it work?

As many other users have pointed out, the answer is simply sqrt(n) * 2. However, calculating the square root in brain-flak is very very nontrivial. Since we know the input will always be a square, we can optimize. So we write a loop that subtracts

1, 3, 5, 7, 9...

from the input, and track how many times it runs. Once it hits 0, the answer is simply the last number we subtracted minus one.

Originally, I had pushed a counter on to the other stack. However, we can use the main stack itself as a counter, by increasing the stack height.

#While TOS (top of stack, e.g. input) != 0:
{

    #Push:
    (

      #The negative of the height of the stack (since we're subtracting)
      [[]]

      #Plus the TOS pushed twice. This is like incrementing a counter by two
      (({}))
    )

#Endwhile
}

#Pop one value off the main stack (or in other words, decrement our stack-counter)
{}

#And push the height of the stack onto the alternate stack
([]<>)

In python-y pseudocode, this is basically the following algorithm:

l = [input]
while l[-1] != 0:   #While the back of the list is nonzero
    old_len = len(l)
    l.append(l[-1])
    l.append(l[-1] - old_len)

l.pop()

print(len(l))

Mathematica, 8 bytes

2Sqrt@#&

Try it online! (Using Mathics.)

The difference between n2 and (n+1)2 is always 2n+1 but we just want the values between them excluding both ends, which is 2n.

This can potentially be shortened to 2#^.5& depending on precision requirements.


Jelly, 2 bytes

½Ḥ

Try it online!

Port of my Mathematica answer (take square root, then double). This is limited to inputs which can be represented exactly as a floating-point number. If that's an issue, the three-byte solution ƽḤ works for arbitrary squares (which Dennis posted first but then deleted).

Tags:

Math

Code Golf