Tất cả thử thách
Trung bình 1 đã giải Tỷ lệ chấp nhận 100.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:
base_value = 8.0
numerator = 1
denominator = 3

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

Kết quả mong đợi:
double expected = 2.0;
Đầu vào:
double base_value = 8.0;
long numerator = 1;
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:
base_value = 16.0
numerator = -1
denominator = 2

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

Kết quả mong đợi:
double expected = 0.25;
Đầu vào:
double base_value = 16.0;
long numerator = -1;
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.

Lời giải đạt tốt nhất của mỗi người. Lời giải nhanh hơn, tốn ít bộ nhớ hơn và được đánh giá cao hơn sẽ đứng trên.

# Người giải Ngôn ngữ Thời gian Bộ nhớ AI đánh giá Lời giải
1 ННикита Python 833 ms - 4/5 Xem code

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

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

Cảnh báo: Có 1 lời giải đầy đủ bên dưới Hãy thử tự giải trước. Bạn vẫn có thể xem mã của người khác và đánh giá AI. Đăng nhập và giải thử thách để tham gia thảo luận.