Trung bình 1 đã giải Tỷ lệ chấp nhận 100.0%

Right-Triangle Product

Find the largest side product of an integer right triangle with a given perimeter.

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

  • Search integer right triangles by perimeter
  • Reduce three loops to two
  • Check the Pythagorean condition

Đề bài

Xem bản dịch

Find positive integers a < b < c with a² + b² = c² and a + b + c = perimeter. Return the largest product a × b × c among qualifying triangles, or −1 if there are none. This generalizes the fixed-perimeter source task and explicitly handles multiple answers.

Implement pythagorean_product(perimeter).

Input

perimeter: The required sum of the three sides.

Output

Return the largest product, or −1 when no triangle qualifies.

Ràng buộc

3 ≤ perimeter ≤ 100,000. Products fit signed 64-bit integers.

Ví dụ

Ví dụ 1
Đầu vào:
perimeter = 30

Kết quả mong đợi:
expected = 780
Đầu vào:
long long perimeter = 30;

Kết quả mong đợi:
long long expected = 780;
Đầu vào:
long perimeter = 30;

Kết quả mong đợi:
long expected = 780;

Giải thích

The triangle is (5, 12, 13): 25 + 144 = 169 and 5 + 12 + 13 = 30. Its product is 780.

Ví dụ 2
Đầu vào:
perimeter = 11

Kết quả mong đợi:
expected = -1
Đầu vào:
long long perimeter = 11;

Kết quả mong đợi:
long long expected = -1;
Đầu vào:
long perimeter = 11;

Kết quả mong đợi:
long expected = -1;

Giải thích

No increasing positive integer right-triangle sides sum to 11.

Hướng tiếp cận

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

Gợi ý 1

Only certain perimeters can form a right triangle, so first narrow the search using the side-sum constraint.

Gợi ý 2

For each possible shortest side, derive the other two sides from the perimeter and check the right-triangle condition.

Gợi ý 3

More than one triangle may fit; keep the largest product and return no-solution when nothing valid appears.

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

O(perimeter^2) 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 957 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.