Python Program to Find Cube Root of a Number
number ** (1/3) or by using pow(number, 1/3).Examples
How to Think About It
** with the fraction 1/3 to calculate this directly in Python.Algorithm
Code
number = float(input("Enter a number: ")) if number >= 0: cube_root = number ** (1/3) else: cube_root = -(-number) ** (1/3) print(f"Cube root of {number} is {cube_root}")
Dry Run
Let's trace the input 27 through the code
Input number
User enters 27, so number = 27.0
Calculate cube root
cube_root = 27.0 ** (1/3) = 3.0
Print result
Output: Cube root of 27.0 is 3.0
| Step | Variable | Value |
|---|---|---|
| 1 | number | 27.0 |
| 2 | cube_root | 3.0 |
| 3 | output | Cube root of 27.0 is 3.0 |
Why This Works
Step 1: Using power operator
The cube root of a number is the same as raising it to the power of 1/3, so number ** (1/3) calculates this directly.
Step 2: Handling negative numbers
Raising a negative number to the power 1/3 returns a complex number in Python, so for negative inputs, we adjust the calculation to keep the result real.
Step 3: Printing the result
We use print with an f-string to show the original number and its cube root clearly.
Alternative Approaches
number = float(input("Enter a number: ")) if number >= 0: cube_root = pow(number, 1/3) else: cube_root = -pow(-number, 1/3) print(f"Cube root of {number} is {cube_root}")
number = float(input("Enter a number: ")) if number >= 0: cube_root = number ** (1/3) else: cube_root = -(-number) ** (1/3) print(f"Cube root of {number} is {cube_root}")
Complexity: O(1) time, O(1) space
Time Complexity
Calculating the cube root using the power operator or pow() is a constant time operation, so it is O(1).
Space Complexity
The calculation uses a fixed amount of memory for variables, so space complexity is O(1).
Which Approach is Fastest?
Using the power operator ** or pow() are equally fast; handling negatives explicitly adds minimal overhead but improves correctness.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Power operator ** | O(1) | O(1) | Simple positive numbers |
| pow() function | O(1) | O(1) | Equivalent to power operator, preference-based |
| Explicit negative handling | O(1) | O(1) | Correct cube roots for negative inputs |
number ** (1/3) for a quick cube root calculation but handle negatives carefully.