Sum Of All Natural Numbers, Below N, That Are Multiples of 3 & 5.

BY indefiniteloop

Problem Statement: Let’s assume n=9. Then, all natural numbers between 1 and 9, that are also multiples of 3 & 5, would be 3, 5, 6, and 9. The summation of these would be 23. Given n, as an integer, the solution should return the summation of all multiples of 3 & 5, between 1, and n.

Test Cases & Kata. Ruby Kata: Add all natural numbers below n, that are multiples of 3 and 5

Here’s How I Solved This Kata In Ruby.

Here’s how I solved the problem of finding the sum of all natural numbers that are multiples of 3, and 5 between 1 and n.

def solution(number)
y=0
(1...number).each { |x| y+=x if x%3==0 or x%5==0 }
return y
end

The Most Precise, And Elegant Solution To This Kata

This one’s by tanzeeb, and some others. And, if you’re aware of select, and inject (I wasn’t aware, until now) in Ruby - this one’s so simple!

def solution(number)
(1...number).select { |i| i%3==0 || i%5==0 }.inject(:+)
end

Some More Thoughts On Solving Katas

Like I mention here, and above. There’s just so much to learn within a give language. Each has it’s own idiosyncrasies, making it all the more interesting to learn. Until I solved this kata, I wasn’t aware of select or inject being available. Again, I am very much in favour of solving katas - precisely so, for the reason of discover, and improving your skills within a given language. This is doubly true if you are coding in multiple languages all the time!

——> Sign yourself up here!

I really do hate spam as much as you. Your email will never be shared with anyone, or any party. That's a pinky promise!

• Extending The Built-In Ruby Classes.

Apr 28, 2016 in Code
• Return Sum Of All Integers Between The Two Unordered Supplied Args

Apr 21, 2016 in Code
• Finding The Next Perfect Square.

Mar 17, 2016 in Code 