Here's an example what 'elegance' means in programming. These are three solutions to a Project Euler problem. All three programs do the same thing-find prime factors of a given number. (I've removed comments). The relative sizes of the scripts are 1.285kb, 0.694kb and 0.139kb respectively.
1)
1)
var biggestPrimeFactor = 1;
var numberToFactor = 600851475143;
var factorArray = []
for (i = 2; i <= Math.sqrt(numberToFactor); i++) {
if(numberToFactor % i === 0) {
factorArray.push(i);
var isPrime = true;
for(j = 2; j <= Math.sqrt(i); j++) {
if(i % j === 0) {
var isPrime = false;
}
}
if(isPrime === true) {
biggestPrimeFactor = i;
}
}
}
for (factor in factorArray) {
var bigFactor = numberToFactor / factorArray[factor];
var isPrime = true
for (i = 2; i <= Math.sqrt(bigFactor); i++)
if(bigFactor % i === 0) {
var isPrime = false;
}
if(isPrime === true) {
biggestPrimeFactor = bigFactor;
}
}
if(biggestPrimeFactor === 1) {
biggestPrimeFactor = numberToFactor;
}
console.log(biggestPrimeFactor);
2)
var i=1;
var largest;
var numtofactor= 600851475143;
var wholecheck;
var remain;
var factorcheck=1;
while(factorcheck!==numtofactor){
if(i%2===0) {
i++;
}
else {
wholecheck=numtofactor/i;
wholecheck=numtofactor/i;
remain = wholecheck-Math.floor(wholecheck);
if(remain===0){
largest=i;
i++;
factorcheck=largest * factorcheck;
}
else {
i++;
}
}
}
console.log(largest);
3)
function solution3 (x) {
for(var i = 2; i < x; i++) {
if (x % i === 0) {
x /= i;
}
}
console.log(x);
}
solution3(600851475143);
This demonstrates a beautiful aspect of information: there are multiple paths to the same answer and there is often a way of achieving more with less. (Mine was the second script, I was proud of it until I found the third one.)
Comments
Post a Comment