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.

Project Euler 43

While working on euler functions, i have managed to come up with quite a library of functions that I use to solve problems.

Today I was playing around with Python 3.0 to see how many of the libraries can be converted, refactored or removed while utilizing the new features of python. First one that can potentially go is the permutations function since itertools now has one.

So here is my ( brute force ) solution to 43 using the permutations from itertools . Takes around 15 seconds to execute


import time
from itertools import permutations


def checkForProperty(t):


if (int(t[1:4])%2) != 0:
return False

if(int(t[2:5])%3) != 0:
return False

if (int(t[3:6])%5) != 0:
return False

if(int(t[4:7])%7) != 0:
return False

if(int(t[5:8])%11) != 0:
return False

if(int(t[6:9])%13) != 0:
return False

if(int(t[7:10])%17) != 0:
return False

return True




r = time.time()

print (sum([int(''.join(x)) for x in permutations('1234567890') if x[0] != '0' and checkForProperty(''.join(x))]))

print (time.time() - r)

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