#!/usr/bin/env python3 # # https://math.stackexchange.com/questions/4271672/given-numbers-1-to-3n-construct-n-equations-of-the-form-a-b-c-or-a import sys def debug(*msgs): # print(*msgs, file=sys.stderr) pass class SearchState(): def __init__(this, used, missed, pool): this.used = used # equations selected so far this.missed = missed # set of numbers not yet covered this.pool = pool # unused equations def __str__(this): return f"{this.used} missing {this.missed}" def extend(this): # Used a solution if len(this.missed) == 0: debug("*", this) yield this.used return debug("- extending", this) # for each possible equation that can be used # add it to the state and attempt to extend to a complete solution pool = set(this.pool) for eqn in pool: debug(".", eqn) if set(eqn) <= this.missed: yield from this.add_equation(eqn).extend() this.pool.remove(eqn) def add_equation(this, eqn): # Just like this, but with eqn added to the list of used equations # and its elements removed from the "missed" set return SearchState(this.used + [eqn], this.missed - set(eqn), this.pool - { eqn }) # equations with numbers up to n def equations(n): eqns = set() for i in range(1, n+1): for j in range(i+1, n-i+1): debug("=", i, j) eqns.add((i, j, i+j)) if i > 1 and i*j <= n: eqns.add((i, j, i*j)) return eqns if __name__ == '__main__': if len(sys.argv) != 2 and len(sys.argv) != 3: print("Usage: x3c number [how-many-solutions]", file=sys.stderr) exit(2) n = int(sys.argv[1]) z = 12 if len(sys.argv) < 3 else int(sys.argv[2]) init = SearchState([], # start with no equations selected set(range(1, n+1)), # numbers 1..n not used yet equations(n) # equations we can use ) for result in init.extend(): print(result) z -= 1 if z <= 0: break