Back to challenges
Medium 0 solved 0% acceptance

Raise a Number to a Fractional Power

Raise a positive real number to a rational exponent.

What you'll learn

  • Turn a rational exponent into a root and a power
  • Use floating-point math safely
  • Handle reduced and negative exponents

Problem

The exponent is numerator / denominator. Raise base_value to that exponent and return the real-valued result. For example, an exponent of 1/3 gives the positive cube root.

Implement real_to_rational_power(base_value, numerator, denominator).

Input

base_value: The positive base.

numerator: The exponent numerator.

denominator: The exponent denominator.

Output

Return base_value raised to numerator / denominator.

Constraints

0.1 ≤ base_value ≤ 100, with at most two decimal places. −6 ≤ numerator ≤ 6; 1 ≤ denominator ≤ 10. Answers are accepted within absolute or relative error 0.000001.

Examples

Example 1
Input:
numerator = 1
base_value = 8.0
denominator = 3

Expected output:
expected = 2.0
Input:
long long numerator = 1;
double base_value = 8.0;
long long denominator = 3;

Expected output:
double expected = 2.0;
Input:
long numerator = 1;
double base_value = 8.0;
long denominator = 3;

Expected output:
double expected = 2.0;

Explanation

2 × 2 × 2 = 8, so the cube root is 2.

Example 2
Input:
numerator = -1
base_value = 16.0
denominator = 2

Expected output:
expected = 0.25
Input:
long long numerator = -1;
double base_value = 16.0;
long long denominator = 2;

Expected output:
double expected = 0.25;
Input:
long numerator = -1;
double base_value = 16.0;
long denominator = 2;

Expected output:
double expected = 0.25;

Explanation

The square root of 16 is 4, and the negative exponent takes its reciprocal, 1/4.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

First turn the exponent fraction into a single real exponent.

Hint 2

Then raise the positive base using a real-power operation.

Hint 3

Make sure negative exponents produce reciprocals, and avoid mistakes with fractional roots.

Expected complexity

O(1) time, O(1) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.