Project-Euler Ruby

What is Project Euler

Project Euler is a website with a collection of programming and mathematical problems. Each challenge varies in difficulty and there are over 600 challenges. I highly recommend anyone interested in puzzles and programming to create an account and start solving. About Project Euler

** Stop here if you have not yet tried and solved Problem 1. **

**

**

**

**

Problem 1

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.

class Problem1
  def question
    "If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
    The sum of these multiples is 23.
    Find the sum of all the multiples of 3 or 5 below 1000."
  end

  def sum_multiples_3_and_5 n
    return 0 if(n <= 1)

    if(n % 3 == 0 || n % 5 == 0)
      n + sum_multiples_3_and_5(n - 1)
    else
      sum_multiples_3_and_5(n - 1)
    end
  end

  def solve
    sum_multiples_3_and_5(999)
  end

  def correct?
    solve === answer
  end

  private

  def answer
    233168
  end
end

 

Did you like this article? Check out these too.


 

Found this useful? Know how it can be improved? Get in touch and share your thoughts at blog@hocnest.com