Re:Ask HN: What's your favorite elegant/beautiful algorithm?
by Sharlin on Wednesday October 17, 2018 @01:03PM
(#18241068)
It is not. There are indeed exactly 8 ways to pick three elements from the set [1,9] such that their sum equals 15. But for 4x4, there are 86 (!) ways to pick four elements from [1, 15] so that their sum is 34 (the magic constant for 4x4), whereas only ten of the combinations are used in construction of the square.
Some Python:
from collections import Counter
from itertools import combinations
def number_of_sums(n, M):
combs = combinations(range(1,n**2+1), n)
sums = (sum(c) for c in combs)
return Counter(sums)[M]
print(number_of_sums(3, 15))
print(number_of_sums(4, 34))
Some Python: