Skip to content

Instantly share code, notes, and snippets.

@libryder
Created February 20, 2012 08:49
Show Gist options
  • Save libryder/1868469 to your computer and use it in GitHub Desktop.
Save libryder/1868469 to your computer and use it in GitHub Desktop.
ProjectEuler solutions
# http://projecteuler.net/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.
sum = 0
(1..999).each do |n|
if n.modulo(5) == 0 || n.modulo(3) == 0
sum += n
end
end
puts sum
# http://projecteuler.net/problem=2
#
# Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
#
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#
# By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
a=b = 1
sum = 0
while b < 4000000
sum += b unless b.odd?
a,b = b,a+b
end
puts sum
# Project Euler: Problem #3 (http://projecteuler.net/problem=3)
#
# The prime factors of 13195 are 5, 7, 13 and 29.
#
#What is the largest prime factor of the number 600851475143 ?
def is_prime? num
prime = true
# limit should be less than half as anything above that will result in < 1
limit = (num/2).floor
(2..limit).each do |n|
if (num%n) == 0
prime = false
break
end
end
prime
end
actual = 600851475143
# The largest prime factor of actual has to be <= the square of actual
start = Math.sqrt(actual).floor
puts start
# start from the top and go down
(start).downto(2) { |n|
if (actual%n == 0) && is_prime?(n)
puts n
break
end
}
# Project Euler: Problem #4 (http://projecteuler.net/problem=4)
#
# A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99.
#
# Find the largest palindrome made from the product of two 3-digit numbers.
#
def is_palindrome? num
num.to_s == num.to_s.reverse! ? true : false
end
largest = 0
999.downto(100) { |x|
999.downto(100) { |y|
product = x*y
largest = product if is_palindrome?(product) && product > largest
}
}
puts largest
# Project Euler: Problem #5 (http://projecteuler.net/problem=5)
#
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
#
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
#
x = 2520
switch = false
while not switch do
(11..20).each { |y| break unless (switch = (x%y == 0)) }
x += 2520
end
puts x
# Project Euler: Problem #6 (http://projecteuler.net/problem=6)
#
# Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
#
puts ((1..100).reduce(:+) ** 2) - (1..100).inject{ |sum, n| sum + n**2 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment