Skip to content

Instantly share code, notes, and snippets.

@Radcliffe
Last active August 29, 2015 14:14
Show Gist options
  • Save Radcliffe/dae8f54c19b1265d312a to your computer and use it in GitHub Desktop.
Save Radcliffe/dae8f54c19b1265d312a to your computer and use it in GitHub Desktop.
Arrange consecutive digits to form two numbers whose product is as large as possible.
# Problem: Arrange the consecutive digits {x,x+1,..,y} to form two numbers A and B
# so that the product A*B is as large as possible.
#
# The generator `splitdigits` returns all candidate triples (P, A, B) where P = A * B.
def splitdigits(x=1, y=9, base=10):
if x == y:
yield (0, y, 0)
else:
for P, A, B in splitdigits(x+1, y, base):
yield (base*P + A*x, A, base*B + x)
yield (base*P + B*x, base*A + x, B)
print max(splitdigits()) # Expected output is (843973902, 9642, 87531)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment