JSFiddle - React, Tailwind, and code Playground
by ktstowell
HTML
<h1><a href="http://projecteuler.net/problem=1">Problem:</a></h1>
<p>
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.
</p>
<p>Find the sum of all the multiples of 3 or 5 below 1000.</p>
<hr />
<div id="sum"></div>
<div id="int-list"></div>
JavaScript
(function(document) {
var i, // Index base - main loop
j, // Index base - divisor loop
cap = 1000, // Limit to search set by question.
quo, // quotient
divs = [3, 5], // Divisors
mlts = [], // List of multiples
mlt_cont = document.getElementById("int-list"), // Div to display
mlt_elem, // Paragraphs to inject into mlt_cont
sum = 0, // Sum of multiples matched
sum_cont = document.getElementById('sum'); // Div to display mult
// Loop through 0-999
for (i=0; i<cap; i++) {
// Find multiples of 3 or 5
for(j=0; j<divs.length; j++) {
// Divide index by each divisor
quo = i / divs[j];
// If the quotient is a whole number
if(quo % 1 === 0) {
// Add formula to the DOM
mlt_elem = document.createElement('p');
mlt_elem.textContent = i + ' / ' + divs[j]+ ' = '+quo + ', Multiple: ' +divs[j];
mlt_cont.appendChild(mlt_elem);
// Process the sum - prevent duplicate entries
// from being totaled
if(mlts.indexOf(i) < 0) {
mlts.push(i);
}
}
}
}
// Total the sum
for(var i=0; i<mlts.length; i++) {
sum += mlts[i];
}
// Add total to DOM
sum_cont.textContent = "Sum: " +sum;
})(document)