D’oh moment from Project Euler

February 12, 2008

I don’t think that the caliber of my posts has necessarily been so high that people will be shocked by overt stupidity from me, but I just discovered some in myself, and stupidity is one of the things that is better shared.

One of the things I’ve had to do very often in Project Euler is figure out whether some long number is an integer or not. So I’ve defined the following function, that I’ve used over and over again:

def is_int(f): return int(f) == f

It actually works pretty well in any number of cases, until the floating point number f starts getting big. However, that doesn’t mean it should be used all of the time.

One place where I’ve used this function incorrectly is figuring out whether a square root is integral, for example, in looking for Pythagorean triplets. It’s much better to test whether a**2+b**2 is square, than whether sqrt(a**2+b**2) is integral. However, since for really huge numbers this requires generating a long list of square integers, I don’t feel too stupid about this. (Does anyone know of a clever way to test whether an integer is a square??)

What I do feel stupid about is in checking whether a rational fraction is integral. I caught myself doing this:


which is staggeringly stupid. I was flipping through some of the forum solutions to Project Euler, and noticed one of the Pythonistas was using the much more intelligent

a % b == 0

One of those things that seems stunningly obvious once you see it, but, for whatever reason, I didn’t see it. (Hangs head in shame.)


3 Responses to “D’oh moment from Project Euler”

  1. […] Snake Food Pedal vehicle for traversing abandoned monorailwaySteve Martin on being funnyLandmarks: What Makes the Stars Shine?MPAA admits to lying about college downloadingA Cold-Weather Anthem for the Cold-Hearted « D’oh moment from Project Euler […]

  2. brennydoogles Says:

    Hmmm… when I did the pythagorean triplets at PE, I wrote the following function:

    def isPythagoreanTriplet(a, b, c):
        if ((a**2) + (b**2)) == (c**2):
            return 1
            return 0

    and then did:

    for a in range(1, 500):
            for b in range(1, 500):
                for c in range(1, 500):
                    if isPythagoreanTriplet(a, b, c) and (a+b+c) == 1000:
                        print "A = %d, B = %d, C = %d," % (a,b,c)
                        return a*b*c

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 )

Google+ photo

You are commenting using your Google+ 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

%d bloggers like this: