Skip to content

Instantly share code, notes, and snippets.

@jgilfillan
Last active August 29, 2015 14:00
Show Gist options
  • Save jgilfillan/c9a66e98411fcc76e662 to your computer and use it in GitHub Desktop.
Save jgilfillan/c9a66e98411fcc76e662 to your computer and use it in GitHub Desktop.
My solution to Project Euler problem 5, using map and reduce.
//QUESTION
//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?
//SOLUTION
// change to 10 to check against PE example
var end = 20;
//generate sequence
var arrSeq = Array
.apply(null, Array(end))
.map(Function.prototype.call.bind(Number))
.map(function(x) { return x + 1; } );
//masterArray will hold the final list of factors to be multiplied together to get the result
var masterArray = new Array(0);
//
function factorise(x) {
var tempArray = Object.create(masterArray); //copy masterArray to tempArray
while (x > 1 && tempArray.length > 0) {
//if factor found, recalculate x to x/factor
if (!(x % tempArray[tempArray.length - 1])) {
x = x / tempArray[tempArray.length - 1];
}
tempArray.pop(); //remove last element in tempArray and go back to start of loop
}
masterArray.push(x); //add x to masterArray
return x;
}
//define function to reduce list of factors to final result
function multiply(r, c) {
return r * c;
}
//perform calculation
var result = arrSeq
.map(factorise)
.reduce(multiply, 1);
//output array of factors and final result
console.log(masterArray);
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment