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

Asked

Viewed 12,373 times

2

It is for python 3:

What I’m looking to do is show the rest of a square-root account that only accepts as many integers as possible as an answer. 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 in this case would 6(The numbers in bold 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 on square root.

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

  • would be something like: radicando = 87 x = math.sqrt(radicando) z = radicando - (2*math.int(x)) print(z)?

  • in case I was wrong here, changes the variable z to z = math.int(x) * math.int(x) in order to take the square from the root, it was bad.

  • Sorry, Armando your code didn’t work, the code I wanted was what Anderson suggested down there, thanks anyway.

  • Wow, @Matheus, so I really wanted to help.

2 answers

8


Just use the mathematical operators // to get the entire 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))))

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

See working on Ideone.

  • It worked. I had already found another way to do it, but its way is much faster and cleaner, thank you very much

5

To answer from Mr Anderson already took my +1, but only to complement follows an alternative without use of the 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 comments of the question).

See working on IDEONE.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.