|
| 1 | +""" |
| 2 | +Project Euler Problem 190: https://projecteuler.net/problem=190 |
| 3 | +
|
| 4 | +Maximising a Weighted Product |
| 5 | +
|
| 6 | +Let S_m = (x_1, x_2, ..., x_m) be the m-tuple of positive real numbers with |
| 7 | +x_1 + x_2 + ... + x_m = m for which P_m = x_1 * x_2^2 * ... * x_m^m is maximised. |
| 8 | +For example, it can be verified that |_P_10_| = 4112 |
| 9 | +(|__| is the integer part function). |
| 10 | +Find Sum_{m=2}^15 = |_P_m_|. |
| 11 | +
|
| 12 | +Solution: |
| 13 | +- Fix x_1 = m - x_2 - ... - x_m. |
| 14 | +- Calculate partial derivatives of P_m wrt the x_2, ..., x_m. This gives that |
| 15 | + x_2 = 2 * x_1, x_3 = 3 * x_1, ..., x_m = m * x_1. |
| 16 | +- Calculate partial second order derivatives of P_m wrt the x_2, ..., x_m. |
| 17 | + By plugging in the values from the previous step, can verify that solution is maximum. |
| 18 | +
|
| 19 | +>>> solution(5) |
| 20 | +10 |
| 21 | +
|
| 22 | +""" |
| 23 | + |
| 24 | + |
| 25 | +def solution(n: int = 15) -> int: |
| 26 | + """ |
| 27 | + Calculate sum of P_m for m from 2 to n. |
| 28 | +
|
| 29 | + >>> solution(2) |
| 30 | + 1 |
| 31 | + >>> solution(3) |
| 32 | + 2 |
| 33 | + >>> solution(4) |
| 34 | + 4 |
| 35 | +
|
| 36 | + """ |
| 37 | + |
| 38 | + ans = 0 |
| 39 | + for m in range(2, n + 1): |
| 40 | + x1 = 2 / (m + 1) |
| 41 | + capital_p = 1.0 |
| 42 | + for i in range(1, m + 1): |
| 43 | + xi = i * x1 |
| 44 | + capital_p *= pow(xi, i) |
| 45 | + ans += int(capital_p) |
| 46 | + return ans |
| 47 | + |
| 48 | + |
| 49 | +if __name__ == "__main__": |
| 50 | + print(f"{solution() = }") |
0 commit comments