divm = 11 n = 11 last = 10**n ssts = [] def setgoodlist(len, adiv): atmp = [0,1,2,3,4,5,6,7,8,9] btmp = [0,1,2,3,4,5,6,7,8,9] for i in atmp: remain = (adiv - i*(10 **(len-1))) % adiv if (adiv - 10*remain) % adiv > 9: btmp.remove(i) return btmp def dropdigs(k,l): ktmp = (k // l) * l ktmp -= 1 while (ktmp % divm) != 0: ktmp -= 1 return ktmp def walking(k): aa = 0 kt = k*10 ktl = kt % last if ((ktl - 1) % divm) + 10 < divm: return aa if ktl % divm == 0: a = kt else: a = kt + (divm - (ktl % divm)) al = a % last if al not in ssts: ssts.append(al) aa = max(aa,a) atmp = walking(a) aa = max(aa,atmp) ssts.remove(al) return aa for n in range(2,12): goodlist = setgoodlist(n,divm) last = 10**n beg = int(n*'9') end = int((n-1)*"9") i = beg while i % divm != 0: i -= 1 an = i oldan = an anlen = n while i > end: ssts = [i] if i % 100000 == 0: anlen = len(str(an)) if anlen > 2*n: anlen = 2*n - 1 an = max(an,walking(i)) i -= divm for j in range(anlen - n+1): jten = 10 ** (n - j-1) if jten < 1: break while (i // jten) % 10 not in goodlist: i = dropdigs(i,jten) print str(n) + " " + str(an)