maxx = 7 def make_iter(x, a, l, lis): for i in xrange(a % 10, 10): if l == x - 1: lis.append(a * 10 + i) else: make_iter(x, a * 10 + i, l + 1, lis) def make(x): if x == 1: return [1,2,3,4,5,6,7,8,9] out = [] for i in xrange(1, 10): make_iter(x - 1, i, 0, out) return out #print make(5) def calc(x): while 1: a = 0 while x != 0: a += (x % 10) ** 2 x /= 10 if a == 1 or a == 89: return a else: x = a #print calc(44) def fac(x): out = 1 for i in xrange(2, x + 1): out *= i return out def alanum(x): x = str(x) out = 1 for i in xrange(maxx, maxx - len(x), -1): out *= i for i in set('.'.join(x).split('.')): tmp = x.count(i) if tmp > 1: out /= fac(tmp) return out #print alanum(113) count = 0 for length in xrange(1, maxx + 1): tmp = make(length) for xx in tmp: if calc(xx) == 89: count += alanum(xx) print count