Showing posts with label project euler python. Show all posts
Showing posts with label project euler python. Show all posts

Saturday, March 14, 2009

Project Euler 63

Some more one liner fun.

I first had the program looking like this:-


total = 0
for x in range(1,10):
for n in range(1,51):
if n == len(str(x**n)):
total += 1
print (total)


After a good look, I was able to reduce it to a 1 liner:-


import time
r = time.time()

print(sum(len(str(x**n)) == n for x in range(1,10) for n in range(1,51)))

print ( time.time() - r )


The parenthesis around print sure does require some getting used to.

Sunday, March 08, 2009

Project Euler #41

After a while I went back to Project Euler to solve a problem. Boy those are addicting. Had some fun with the fairly simple #41

The idea was to find the largest n-digit pandigital that is also a prime. A n-digit number is pandigital if it makes use of all the digits 1 to n exactly once

Based on the simple isPrime rule I was able to rule out 8 digit and 9 digit pandigitals. This is because the sum of the numbers is evenly divisible by 9, sum(1..9) = 45 and sum(1..8) = 36. So this left me with the possibility that n <= 7 .

Here is the python code I used to find it:-


def isNPandigital(number):
return set( [int(c) for c in str(number)]) == set(range(1,len(str(number))+1))


t = time.time()
primes = sieve(7654321)
answerSet = []

print "primes generated"

for prime in primes:
if isNPandigital(prime):
answerSet.append(prime)

print max(answerSet)
print time.time() - t