Quay lại danh sách thử thách
Trung bình 0 đã giải Tỷ lệ chấp nhận 0%

Raise a Number to a Fractional Power

Raise a positive real number to a rational exponent.

Bạn sẽ học được gì

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

Đề bài

Xem bản dịch

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.

Ràng buộc

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.

Ví dụ

Ví dụ 1
Đầu vào:
numerator = 1
base_value = 8.0
denominator = 3

Kết quả mong đợi:
expected = 2.0
Đầu vào:
long long numerator = 1;
double base_value = 8.0;
long long denominator = 3;

Kết quả mong đợi:
double expected = 2.0;
Đầu vào:
long numerator = 1;
double base_value = 8.0;
long denominator = 3;

Kết quả mong đợi:
double expected = 2.0;

Giải thích

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

Ví dụ 2
Đầu vào:
numerator = -1
base_value = 16.0
denominator = 2

Kết quả mong đợi:
expected = 0.25
Đầu vào:
long long numerator = -1;
double base_value = 16.0;
long long denominator = 2;

Kết quả mong đợi:
double expected = 0.25;
Đầu vào:
long numerator = -1;
double base_value = 16.0;
long denominator = 2;

Kết quả mong đợi:
double expected = 0.25;

Giải thích

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

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

First turn the exponent fraction into a single real exponent.

Gợi ý 2

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

Gợi ý 3

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

Độ phức tạp mong đợi

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

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Học hỏi từ người khác

Giải pháp cộng đồng

Chưa có giải pháp nào được chia sẻ. Hãy giải thử thách này để đăng giải pháp đầu tiên.