A census worker visits the home of a woman. After he knocks on her door, she answers and he can see three kids behind her. He asks about the ages of the children. She says, “The product of their ages is 72. And the sum of their ages is the number on the door.” He checks the door, thinks about it a minute, and then says “I need more information.” She replies, “The oldest one likes strawberries.” He immediately figures out their ages.
How old are the children?
While this can certainly be done without a computer program, I used a program because it was more fun.
From the text, we can assume that whatever the house number is, there are at least two ways to have 3 integers whose product is 72 and whose sum is the house number. Furthermore, it is apparent that in only one of the ways of having such a product will we find the oldest child not be a twin.
The program finds that only in the case of the sum being 14 are there two ways the children's ages could be distributed and multiply to 72:
[2, 6, 6] or [3, 3, 8], but only in the latter is the eldest child not a twin.
Solution: the children are 3, 3, and 8
-----------------------
def factors(n):
""" for integer n, return a list of all the factors including 1 and n """
ans = [1,n]
for i in range(2,2+int(n**.5)):
if n%i == 0:
ans.append(i)
ans.append(int(n/i))
ans = sorted(list(set(ans)))
return (ans)
factorsOf72 = factors(72)
agesBySumDict = {}
from itertools import combinations_with_replacement
for comb in combinations_with_replacement(factorsOf72, 3):
if comb[0]*comb[1]*comb[2] != 72:
continue
x = sorted(list(comb))
mysum = sum(x)
if mysum not in agesBySumDict:
agesBySumDict[mysum] = [x]
else:
agesBySumDict[mysum].append(x)
for asum, aset in agesBySumDict.items():
if len(aset) == 1:
continue
print(asum, aset)
---- output
14 [[2, 6, 6], [3, 3, 8]]
|
Posted by Larry
on 2024-03-29 09:47:15 |