Skip to content

Instantly share code, notes, and snippets.

@benjaminoakes
Last active March 22, 2017 14:31
Show Gist options
  • Save benjaminoakes/30d3a23dda90bb37b764e37d0bb04d8c to your computer and use it in GitHub Desktop.
Save benjaminoakes/30d3a23dda90bb37b764e37d0bb04d8c to your computer and use it in GitHub Desktop.
Project Euler
function find(start, finish, qualifier) {
var index;
for (index = start; start <= finish; index++) {
if (qualifier(index)) {
return index;
}
}
}
function primeFactors(number) {
var factors, factor;
if (1 === number) {
return [];
} else {
factor = find(2, number, function (potentialFactor) {
return 0 === number % potentialFactor;
});
return primeFactors(number / factor).concat(factor);
}
}
function largestPrimeFactor(number) {
return primeFactors(number)[0];
}
console.log(largestPrimeFactor(13195));
console.log(largestPrimeFactor(600851475143));
# 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 assert(boolean)
raise 'assertion failed' unless boolean
end
def palindrome?(stringable)
string = String(stringable)
string == string.reverse
end
assert palindrome?('otto')
assert palindrome?(1)
assert palindrome?(101)
assert palindrome?(9009)
puts (100..999).
map { |i| (100..999).map { |j| i * j } }.
flatten.
select { |n| palindrome?(n) }.
sort.
last
# 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?
# n = (1..999999999).find { |i| (1..20).all? { |j| 0 == i % j } }
# puts n
primes = [1, 2, 3, 5, 7, 11, 13, 17, 19]
non_primes = [4, 6, 8, 10, 12, 14, 15, 18, 20]
prime_product = primes.reduce { |a, e| a * e }
puts prime_product * non_primes[0] * non_primes[1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment