1 2 3 4 5 6 7 8 9 10 11 12 |
# Let n bags be original number of bags of sweet bought # Let c pence be original cost per bag in pence # Let m be number of bags at 12 pence less than original cost for n in range(1, 100): for c in range(1, 100): for m in range(1, 100): if (n * c > 50 and n * c == (n + 2) * (c - 9) and n * c == m * (c - 12)): print(f"Total sweet cost was {n * c} pence") |

1 2 3 4 5 6 7 8 9 10 11 12 |
# try the divisors of 64 (2^n for n in 0..6) for x in range(7): f = 2 ** x n, r = divmod(32 // f + 2, 3) p = 9 * (n + 2) // 2 # the sweets cost more than 50 pence if not r and n * p > 50: z = zip((0, 2, (f + 16) // 6), (0, 9, 12)) s = ', '.join(f"{n + x} bags @ {p - y}p" for x, y in z) print(f"Total cost £{n * p / 100:.2f} ({s}).") |

It is also easy to derive an alternative formulation which gives: \[\begin{eqnarray} p\;&=&\;9k \\ n\;&=&\;2(k-1) \\ c\;&=&\;18k(k-1) \\

m\,&=&\;6k(k-1)/(3k-4)\end{eqnarray}\]for integer \(k\), which gives the solution for \(k=4\)