在Python中(这不是你问的,但你更需要一个算法):
import operator
import itertools
possible_ages = range(2,15)
# If the list of ages passed to this function returns true, then this solves the puzzle.
def valid(ages):
product_of_ages = reduce(operator.mul, ages, 1)
square_of_sum_of_ages = reduce(operator.add, ages, 0) ** 2
return product_of_ages == square_of_sum_of_ages
for number_of_children in range(1, 9):
for ages in itertools.combinations(possible_ages, number_of_children):
if valid(ages):
print ages
Run Code Online (Sandbox Code Playgroud)
并且几乎立即打印:
(2, 4, 6, 12)
Run Code Online (Sandbox Code Playgroud)