Teaser 2778: Cold turkey
From The Sunday Times, 20th December 2015 [link] [link]
We are having a “cold turkey” party on Boxing Day. Fewer than 100 people have indicated that they are coming, and the percentage of them choosing the vegetarian option is (to the nearest whole number) a single-digit number. My vegetarian aunt might also come. If she does, then (to the nearest whole number) the percentage having the vegetarian option will remain the same.
If she does come, how many people will be there and how many of them will have the vegetarian option?
[teaser2778]
Jim Randell 8:48 am on 4 March 2021 Permalink |
This Python program runs in 47ms.
Run: [ @repl.it ]
from enigma import divf, irange, printf # percentage a/b to the nearest whole number percent = lambda a, b: divf(200 * a + b, 2 * b) # total number of people expected (including aunt) for n in irange(2, 100): # consider number of vegetarians for v in irange(1, n): # percentage vegetarians (to nearest whole number) p = percent(v, n) if p > 9: break # and if aunt doesn't come, is percentage the same? if percent(v - 1, n - 1) == p: # output solution printf("{n} total; {v} veg [{p}% veg]")Solution: If the aunt comes there will be 95 people in total. 9 of them vegetarian.
In this case the percentage of vegetarians is 9/95 ≈ 9.47%, which rounds down to 9%.
But if the aunt doesn’t come both the number of guests and the number of vegetarians is reduced by 1, giving a percentage of 8/94 ≈ 8.51%, which rounds up to 9%.
Note that Python 3’s built-in [[
round()]] function might not do what you expect:The
decimalmodule allows more control over rounding behaviour.To keep things predictable, in my program I avoided float approximations by keeping the calculations in the integer domain, and I used the common “round half up” rule.
LikeLike