I am trying to solve problem 41, but i don’t know why my code stops at 987654319:
def IsPandigital(No):
a = sorted(str(No))
for i in range(1,10):
if a[i - 1] != str(i):
return False
return True
def IsPrime(No):
i = 2
while i < No:
if No % i == 0:
return False
i += 1
return True
i = 987654321
while i > 0:
print i
raw_input()
if IsPrime(i) == True and IsPandigital(i) == True:
print i
break
i -= 1
print i
print "EOP"
raw_input()
P.S: I know that i should start from 799999999 because:
GergS: Every 9 digit and 8 digit pandigital number is divisible by 3.
Your
IsPrimefunction is very slow. It quickly calculated that 987654321 is dividable by 3 and 987654320 is dividable by 2. However, 987654319 is prime and it takes very very long to check it against all divisors so it seems as if it stopped.The problem requires more than just simple calculation, as you did. Calculating prime numbers is a slow process, so you should optimize it, for example:
IsPandigitalbeforeIsPrime,pandigital numbers and make the prime
test. Hint: the pandigital numbers are:
[987654321,987654312,987654231,987654213,...]while i <– it is enough to go up toNo
sqrt(No).Your other problems: