When an input number is given as input. The input digit should be read and nearest cubic root value will be displayed as output

47 views Asked by At

For example:

Input = 21

Nearest cubic root values for above digit are: 2 and 3

  • 8 = 2*2*2
  • 27 = 3*3*3

Among those values, 27 is nearer to 3, so it should be displayed as output.

1

There are 1 answers

0
Mushroomator On

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:
    • 2
    • 3
  • Their cubed values
    • 2 ** 3 = 8
    • 3 ** 3 = 27
  • Difference to given number 21
    • | 8 - 21 | = 13
    • | 27 - 21 | = 6
  • Smallest difference
    • 6 which is obtained when cubing 3 so print 3

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