'When an input number is given as input. The input digit should be read and nearest cubic root value will be displayed as output
For example:
Input = 21
Nearest cubic root values for above digit are: 2 and 3
8 = 2*2*227 = 3*3*3
Among those values, 27 is nearer to 3, so it should be displayed as output.
Solution 1:[1]
I believe you are mixing up digit with number. Digits are just 0-9.
Having said that, from the description you are giving I believe you want to compute the smallest difference between a given number (e.g. 21) and the cubed values of the closest two integer values to the cubic root of said number.
So for 21 it would be:
- Cubic root =
21 ** (1/3) ~ 2,75 - Two closest integers:
23
- Their cubed values
2 ** 3 = 83 ** 3 = 27
- Difference to given number
21| 8 - 21 | = 13| 27 - 21 | = 6
- Smallest difference
6which is obtained when cubing3so print3
Here a Python script that will do exactly that.
import sys
# helper function to check whether a string can be parsed as float
def represents_float(s):
try:
int(s)
return True
except ValueError:
return False
# ask user to input a number
number_str = input("Please enter a number: ")
if not represents_float(number_str):
print("You must enter a number")
sys.exit(1)
number = float(number_str)
# calculate cubic root
cubic_root = number ** (1/3)
# get closest int values
smaller = int(cubic_root)
bigger = smaller + 1
# calculate difference
smaller_diff = abs(smaller ** 3 - number)
bigger_diff = abs(bigger ** 3 - number)
# print the one with smaller difference
if smaller_diff < bigger_diff:
print(smaller)
else:
print(bigger)
Expected output (if entering 21)
Please enter a number: 21
3
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 | Mushroomator |
