-2

numbers are real long, (for example n=341235129628026803631240389584456), I tried that way: if n**(1/2)-floor(n**(1/2)) == 0: true but program count n**(1/2) like 1.8472550707144556e+16, but i need number without e

1 Answers1

1

You can do it with binary search.
Function f(x) = x2 is monotonically increasing for x = 1, 2, ..., k, ... (i.e. natural numbers). Therefore, equation f(m) = m2 = n has at most one root (with respect to m), which you can find by binary searching.
It will require O(log3(n)) operations (because there are O(log(n)) iterations of BS, each one requires squaring, which can be done in O(log2(n))).

The implementation may look like this:

def find_if_square(n):
  L, R = 0, n + 1
  while R - L > 1:
    M = (R + L) // 2
    if M * M <= n:
      L = M
    else:
      R = M

  return L * L == n

Here we maintain an invariant: L2 &leq; n < R2. The distance between L and R decreases until R = L + 1. Then we only need to check whether L2 is strictly equal to n (otherwise, it is less, according to our invariant).

Mike Koltsov
  • 336
  • 3
  • 6