Skip to content

Instantly share code, notes, and snippets.

@bencooper222
Created October 8, 2017 08:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bencooper222/2d3854a59d2e55d73a0755c9adb280c9 to your computer and use it in GitHub Desktop.
Save bencooper222/2d3854a59d2e55d73a0755c9adb280c9 to your computer and use it in GitHub Desktop.
Counting the number of occurrences of each parity among a range of adjacent integers
let start = 1;
let end = 123456789;
let evenCount = 0;
let oddCount = 0;
for (let i = start; i <= end; i++) {
if (isEven(sumDigits(i))) {
evenCount++;
} else {
oddCount++;
}
if (i % 1000 === 0) {
console.log(100 * ((i - start) / (end - start)) + " % complete!");
}
}
console.log("Even: " + evenCount);
console.log("Odd: " + oddCount);
function sumDigits(number) {
var str = number.toString();
var sum = 0;
for (var i = 0; i < str.length; i++) {
sum += parseInt(str.charAt(i), 10);
}
return sum;
}
function isEven(n) {
return n % 2 == 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment