I am trying to write a recursive solution for a program to find a number where the first N digits are divided by N.
As an example: 3816547290, 3 is divided by 1, 38 is divided by 2, 381 is divided by 3, and so on ...
A recursive solution works fine when switching to "recursion", but it has problems when a packet breaks up (i.e. I donโt know how to backtrack or take steps at the exit
ARR = [0]*10 ARR[0] = 1 #dummy entry def numSeq(pos, num): if all(ARR): print num return True if (pos>0) and (num%pos) != 0: return False for i in xrange(1,10): if ARR[i] == 1: continue new_num = num*10 + i if new_num%(pos+1) == 0: ARR[i] = 1 numSeq(pos+1,new_num)
The problem with this code, apparently, is that it correctly follows the order of the number when it goes to recursion ... therefore it correctly generates the number 123654, which is divisible by 6 and it follows that the first N digits are divisible by N, but after he canโt find any further digits from 7-8 or 9 that divide 7, I donโt get the next set of steps to โresetโ the global ARR and start at index 2, i.e. trying 24xxxx, and finally 3816547290
Thanks to Advance for your help!
EDIT . One of the conditions that I forgot to mention is that each digit must be used exactly once (that is, repeating the digits is forbidden)
2nd EDIT :
I finally managed to apply the correct rollback to solve the problem ... this code works as it is.
ARR = [0]*10 def numDivisibile(num,pos): if all(ARR): print num return True for i in xrange(0,10): if ARR[i] == 1: continue new_num = num*10+i