Home - riemann79/hello-world GitHub Wiki
Project Euler Problem 8
The first implementation extracts a substring of the desired length starting from the current position in the string. The program loops the characters in the substring, converts them to integers and computes the product of the integers. The result is the maximum product.
var max = 0;
var winLength = 13;
var str = data.replace(/\n/g, "");
for(var i = 0; i < str.length - winLength; i++) {
var pattern = str.substr(i, winLength);
var prod = 1;
for(var j = 0; j < pattern.length; j++) {
prod = prod * parseInt(pattern[j]);
}
if(prod > max) {
max = prod;
}
}
A first improvement (in memory usage) can be made by avoiding to extract the "sliding window" into a new string.
var str = data.replace(/\n/g, ""),
winLength = 13,
max = 0;
for(var i = 0; i < str.length - winLength; i++) {
var prod = 1;
for(var j = i; j < winLength + i; j++) {
prod = prod * parseInt(str[j]);
}
if(prod > max) {
max = prod;
}
}
A further improvement (in speed) can be made by introducing an early exit in the loop when str[j] === 0. In this case, the product would be equal to 0 and thus can be ignored.
var str = data.replace(/\n/g, ""),
winLength = 13,
max = 0;
for(var i = 0; i < str.length - winLength; i++) {
var prod = 1;
for(var j = i; j < winLength + i; j++) {
if(str[j] === '0') {
break;
}
prod = prod * parseInt(str[j]);
}
if(prod > max) {
max = prod;
}
}
Another improvement in speed results from the following iterative formula that express a n-digits product in terms of the previous computed n-digits product.
p_(j) = p_(j - 1) * str[j] / str[j - 1]
valid when j > winLength - 1 and when str[j - 1] != 0. Thus, the expression must be reset whenever we encounter a 0.
var str = data.replace(/\n/g, ""),
winLength = 13,
max = 0,
iterations = 0,
prod = 1;
for(var i = 0; i < str.length; i++) {
if(str[i] === '0') {
prod = 1;
iterations = 0;
continue;
}
if(iterations > winLength - 1) {
prod = prod / parseInt(str[i - winLength]);
}
prod = prod * parseInt(str[i]);
if(prod > max) {
max = prod;
}
iterations++;
}