Saturday, January 24, 2009

My first Python program!

Below is my first Python program that I wrote from scratch to solve a problem I had. I was working with my son to come up with prime numbers. We got up to 100, and then our brains just started hurting when trying to figure out whether 101 were prime or not. Then I fired up a spreadsheet program to answer the problem. It was only a little bit more helpful than doing it by hand. Then I realized that Python could to it.

So I fired up a text editor and wrote this little program. It works!!
//begin Python program


primecounts=0;
for i in range (1,1e3):
    isntprime=0;
    for j in range (1,i):
        for k in range (1,j):
            if j*k==i:
                isntprime=isntprime+1
    if isntprime==0:
        primecounts=primecounts+1
        print i
print "The number of primes less than "
print i+1," is ", primecounts

No comments: