Solution to Prob #44

The problem statement is here. I solved this problem a couple of days back trying to use lists and minimize the number of computations. Eventually, i found that the list could be a tad more expensive than the computation :D . Here is my final version of the solution, faster than I expected!

from math import sqrt

pentagonal = lambda n: n*((3*n)-1)/2

def is_pentagonal(num) :
    if num == 0 :
        return False
    n = int((1 + sqrt((1 + (24*num))))/6)
    return pentagonal(n) == num

# 1560090 7042750
#
if __name__ == '__main__' :

    max = 10
    done = False
    while not done:
        for i in xrange(2, max) :
            pi = pentagonal(i)
            for j in xrange(2, max) :
                pj = pentagonal(j)
                if not is_pentagonal(pi+pj) :
                    continue
                if is_pentagonal(abs(pi-pj)) :
                    print pi, pj
                    done = True
                    break
            if done :
                break
            max += 10

Some of this has no explanation:
Why am I moving in steps of 10?
No logic there, just happen to like ten.

How does this guarantee that the difference is minimal?
Well, I dunno. I did not even see if there are other numbers :D :D

Advertisement

About abiya

An electrical engineer by education, was a software engineer until some time back and am now a student of electrical engineering again. I :watch the television a lot; don't go to the movie too often; used to play tennis; program using python; I read pulp fiction and my favorites include Atlas Shrugged, GodFather, Silence of the Lambs etc..

Posted on October 3, 2010, in projecteuler, python, technical and tagged , . Bookmark the permalink. Leave a Comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.