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
Ruby Kata: Add all natural numbers below n, that are multiples of 3 and 5

View Kata & Test Cases

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!

Solve This Kata




About The Author:

Home Full Bio