Skip to content

Instantly share code, notes, and snippets.

@pjc
Created July 1, 2012 22:41
Show Gist options
  • Save pjc/3029906 to your computer and use it in GitHub Desktop.
Save pjc/3029906 to your computer and use it in GitHub Desktop.
Euler Project in Ruby - Problem 5
upto = 20
def prime? x
(2..x-1).each { |y| return false if x % y == 0 }
true
end
# For speed reasons we want to find max possible increment
def increment upto
a = 1
(1..upto).each { |x| a*= x if prime? x }
a
end
def no_remainder? x, upto
(1..upto).each { |y| return false if x % y != 0 }
true
end
increment = increment upto
x = increment
try_number = 1
while true
if no_remainder? x, upto
puts "The smallest number is #{x}"
break
end
try_number += 1
x = try_number * increment
end
@nadeemyasin61
Copy link

Another clean and quick thing in Ruby.

def compute_lowest_dividing_number number
  for i in 2..(number/2)
    return i if number%i == 0
  end
  number
end

lcm = 1
n = 20
for i in 1..n
  # look ahead appraoch
  next_number = [i+1, n].min
  lcm *= compute_lowest_dividing_number(next_number) if lcm % next_number != 0
end
puts lcm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment