Here is how, this is the best way, I have found:
x = int(raw_input("Enter an integer: ")) for ans in range(0, abs(x) + 1): if ans ** 3 == abs(x): break if ans ** 3 != abs(x): print x, 'is not a perfect cube!' else: if x < 0: ans = -ans print 'Cube root of ' + str(x) + ' is ' + str(ans)
Is there a better way, preferably one that avoids having to iterate over candidate values?
Python Get Cube Root Using the Exponent Symbol ** For example, the cube root of integer -27 should be -3 but Python returns 1.5000000000000004+2.598076211353316j .
The pow() function finds the cube of a number by giving the values of i and number. ex: pow(i,3).
sqrt() function is an inbuilt function in Python programming language that returns the square root of any number. Syntax: math. sqrt(x) Parameter: x is any number such that x>=0 Returns: It returns the square root of the number passed in the parameter.
You could use x ** (1. / 3)
to compute the (floating-point) cube root of x
.
The slight subtlety here is that this works differently for negative numbers in Python 2 and 3. The following code, however, handles that:
def is_perfect_cube(x): x = abs(x) return int(round(x ** (1. / 3))) ** 3 == x print(is_perfect_cube(63)) print(is_perfect_cube(64)) print(is_perfect_cube(65)) print(is_perfect_cube(-63)) print(is_perfect_cube(-64)) print(is_perfect_cube(-65)) print(is_perfect_cube(2146689000)) # no other currently posted solution # handles this correctly
This takes the cube root of x
, rounds it to the nearest integer, raises to the third power, and finally checks whether the result equals x
.
The reason to take the absolute value is to make the code work correctly for negative numbers across Python versions (Python 2 and 3 treat raising negative numbers to fractional powers differently).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With