Sunday Times Teaser 2531
by Graham Smithers
Published: 27 March 2011 (link)
A Harshad number (or H-number) is any number that is divisible by the sum of its digits. Using each non-zero digit just the once, I have written down a 9-figure H-number. Reading from left to right, it also consists of three 2-figure H-numbers followed by a 3-figure H-number. Again working from left to right through the 9-figure number, the last five digits form a 5-figure H-number. Reversing the order of the first five digits of the 9-figure number also gives a 5-figure H-number.
What is the 9-figure number?
One Comment
Leave one →
-
Brian Gladman permalink123456789101112131415161718192021222324252627282930from itertools import permutationsfrom functools import reduce# return true if digits from i to j - 1 inclusive# from the sequence 'seq' form a Harshad numberdef is_h(seq, i, j):nbr = reduce(lambda x, y: 10 * x + y, seq[i:j])return not nbr % sum(x for x in seq[i:j])# permute digits for the right hand five digitsfor p in permutations(range(1, 10), 5):# test the right hand 2, 3 and 5 digit Harshad numbersif is_h(p, 0, 5) and is_h(p, 0, 2) and is_h(p, 2, 5):# permute digits for the left hand four digitsfor q in permutations(set(range(1, 10)).difference(p)):# test the two left hand 2 digit Harshad numbersif is_h(q, 0, 2) and is_h(q, 2, 4):# now form the full nine digit number and test# that it and its first 5 digit reversed are# both Harshad numbersqp = q + pif is_h(qp, 0, 9) and is_h(qp[::-1], 4, 9):nbr = reduce(lambda x, y: 10 * x + y, qp)print('The number is {}.'.format(nbr))