A Little Off Code, Computers, Photography and Guns

19Feb/090

Programming for *wait for it* the fun of it

Most of my friends think that there's something wrong with me, most of them have had programming experience before with at least one class, some of them more programming than that, but the real reason they think there's something wrong with me is that I enjoy programming. Occasionally they'll ask me what I'm up to and when I tell them that I'm programming, they assume it's for a class of some kind but recently it's only been for entertainment//fun. None of them seem to understand how I could possibly enjoy programming. To be completely honest I don't really know myself why I enjoy it so much.

Lately I've been fooling around with Python's functional programming which is pretty limited in terms of pure functional programming but is still interesting. Take the following code for example:

1
2
3
4
5
6
7
8
def GetPrimes(p, i=1):
    if i**2 < p[-1]:
        p[i:] = filter(lambda x: x % p[i-1] != 0, p[i:])
        return GetPrimes(p, i + 1)
    return p

print GetPrimes(range(2,51))
#[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

This was an example I spent about an hour one night coding. It was brought about by a friend of mine that is in a physics computation course that introduces students to the C programming language and it's applications in science. One of the first problems they were given was to determine whether an integer was a prime number or not.

The python blurb I came up with is a short implementation of the Sieve of Eratosthenes. The basic principle of the Sieve of Eratosthenes is that given a list of integers between 2 and the number you wish, you can find all the primes by simply crossing out multiples.

  • Start with 2, remove all multiples of 2 from the list.
  • Move to the next item in the list, this must be a prime
  • Starting on this number's square (since all of the numbers between this number and it's square have already been crossed out) cross out all multiples of this number.
  • Continue until we reach a number in the list such that it's square is greater than the largest integer in this list.

According to the Wikipedia article on this method for finding primes it's useful for "small primes" such as all primes below 10,000,000. The main point of this is just that I found it fascinating and wasted enough time on it to produce a working function to do this...