how to find multiples of two numbers not exceeding some n? in ruby

To find the multiples of two numbers not exceeding a given n in Ruby, you can use a loop and an array to store the results. Here's an example code:

main.rb
def find_multiples(num1, num2, max)
  multiples = []

  (1..max).each do |i|
    if i % num1 == 0 || i % num2 == 0
      multiples << i
    end
  end

  multiples
end

# Example usage
num1 = 3
num2 = 5
max = 20

result = find_multiples(num1, num2, max)
puts result.inspect  # Output: [3, 5, 6, 9, 10, 12, 15, 18, 20]
317 chars
20 lines

In the above code, the find_multiples method takes three arguments: num1, num2, and max. It initializes an empty array called multiples to store the multiples. Then, using a loop, it checks if each number from 1 to max is divisible by either num1 or num2. If it is, the number is added to the multiples array. Finally, the array is returned as the result.

You can call the find_multiples method with your desired values and store the result in a variable. In the example above, the multiples of 3 and 5 not exceeding 20 are [3, 5, 6, 9, 10, 12, 15, 18, 20].

related categories

gistlibby LogSnag