square root "perfect" in python and identify the rest:

2

It's for python 3:

What I'm trying to do is show the rest of a square root account that only accepts the largest integer possible in response. For example:

import math

x=math.sqrt(87)

print(x)

This code returns 9.327379053088816, I want my code to return only 9 and show me the rest that would be 6 (the bold numbers are the ones I want appearing) since 9² = 81 and 87-81 = 6 ... would be + - what the function + + the function // do in the division. Only now in the square root.

I think I explained what I want the best I could, can anyone help me in this crazy XD request?

    
asked by anonymous 26.08.2017 / 09:32

2 answers

6

Just use the // mathematical operators to get the integer division and % to get the rest of the division. See the example:

import math

value = 87
sqrt = math.sqrt(value) # 9.327379053088816

div = value // sqrt  # 87 // 9.327379053088816 = 9
mod = value % div    # 87 % 9 = 6

print(div, mod)

Alternatively you can do something like:

print(divmod(value, int(math.sqrt(value))))

What, for practical purposes, is equivalent to the previous code.

  

See working at Ideone .

    
26.08.2017 / 13:48
4

The colleague Anderson's answer already took my +1, but only to complement follows an unused alternative module:

import math

value = 87

sqrt = int(math.sqrt(value))
remainder = value - (sqrt * sqrt)


print(sqrt, remainder)

In this version we are rounding the root ( sqrt ) and calculating the rest "primitively", subtracting the perfect root from the original value (similar to the method used by colleague Armando in the question comments).

  

See working at IDEONE .

    
26.08.2017 / 20:55