Saturday, August 6, 2011

Learning Python with Project Euler: Problem 1

This one is short and simple. There was really nothing to learn as far as Python goes, the constructs are similar to Ruby, though I'm sure there's a nicer way to write it. I'll also write my Ruby implementation which is a littler shorter. I'll likely try to write more efficient implementations in both languages.

The problem:
Add all the natural numbers below one thousand that are multiples of 3 or 5.

My Python implementation:
vsum, i = 0, 0
while i < 1000:
  vsum += i if i % 3 == 0 or i % 5 == 0 else 0
  i += 1
print 'sum: ' + str(vsum)

My Ruby implementation:
sum = 0
(0...1000).each { |v| sum += (v % 3 == 0 or v % 5 == 0) ? v : 0 }
puts "sum: #{sum}"

Contribution by Lov Loothra (250+ times faster than mine):
import sys
def main():
    N = 999

    #sum of all multiples of 3 < 1000
    sum3 = (N/3*(N - N%3 + 3))/2

    #sum of all multiples of 5 < 1000
    sum5 = (N/5*(N - N%5 + 5))/2

    #sum of all multiples of 3 & 5 (i.e. 15) < 1000
    sum15 = (N/15*(N - N%15 + 15))/2

    #final result
    print sum3 + sum5 - sum15

Introduction

Welcome to my first blog.  I'm tentivly naming is "Coding Problems", though I can't guarantee it'll be strictly about coding and programming, but that'll probably be the main topic.

I have a strong interest in computer science and mathematics. I'm particularly interested in the software engineering side of computer science, where engineers use and develop techniques to increase productivity and the overall quality of their code. I figure by documenting some experiences I have with programming, I'll not only have a nice log of my experiences to look bad on someday, but maybe others will find it helpful or interesting.

I'm mostly skilled in Ruby and Java.  Though I have exposure to several other languages, including but not limited to C, Python, PHP, VB.NET, and Haskell.  I'm very interested in functional languages.  I'd love to become skilled in Haskell someday; what I did taught myself a couple years back was a blast, but unfortunately I didn't stick with it.  I'm also interested in learning Scala, Closure, and/or Groovy.  Professionally I work with Ruby, VB.NET, PHP, Java, MySQL, TSQL, and scripting languages.