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
I've posted a purely mathematical solution to this on Pastebin: http://pastebin.com/vgGBkJ3M
ReplyDeleteAwesome, very clever! I can't believe I didn't think to try a mathematical-only approach. I've been shamed since I do have a B.S. in mathematics.
ReplyDeleteBy comparison, your mathematical solution is about ~250 times faster (though my benchmark could be flawed, I wouldn't be surprised if it was actually more than that). If you don't mind, I'd like to post your solution here for future reference if that pastebin gets deleted.
Thanks for posting my solution! Please feel free to post, use or critique any code I share. Feedback and sharing is the only way we can learn! :)
ReplyDeleteAnd the only reason I thought of that solution was cause I'm prepping math for some tests I have to take in a couple of weeks. :P