'Cubic Root in python without using the power operator
I need your help in the following question
Print the greatest integer whose cube is smaller or equal to the input number without using the power operator ,you must use the print function and match the expected output :
Print the following for input n=99: 4,not exact with difference 35
Print the following for input n=2000: 12,not exact with difference 272
Print the following for input n=1000: 10, exact!
def cubic_root(n): if n<0: n=abs(n) cube_root = n**(1/3)*(-1) else: cube_root = n**(1/3) diff = round(n-(cube_root *cube_root *cube_root )) print (cube_root,"not exact with",diff) return cube_root print(round(cubic_root(99))) print(round(cubic_root(2000))) print(round(cubic_root(1000)))
My output:
4 not exact with 35
4
12 not exact with 272
12
9 not exact with 271
9
Solution 1:[1]
def cubic_root(n):
n=abs(n)
result=1
x=2
if n==0:
print('0, exact!')
elif n==1:
print('1, exact!')
else:
while result<n:
result=x*x*x
if result>=n:
break
x=x+1
if result!=n:
x=x-1
diff=(x*x*x)-n
if diff==0:
print('{0}, exact!'.format(str(x)))
else:
diff=abs(diff)
print('{0}, not exact with difference {1}'.format(str(x), str(diff)))
Solution 2:[2]
def cubic_root(n):
n=abs(n)
result=1
x=2
if n==0:
print('0, exact!')
elif n==1:
print('1, exact!')
else:
while result<n:
result=x*x*x
if result>=n:
break
x=x+1
if result!=n:
x=x-1
diff=(x*x*x)-n
if diff==0:
print('{0}, exact!'.format(str(x)))
else:
diff=abs(diff)
print('{0}, not exact with difference {1}'.format(str(x), str(diff)))
n = int(input("enter the value: ")) cubic_root(n)
##this worked for me
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | mhmd ali Mhanna |
