Skip to content

Instantly share code, notes, and snippets.

@selbyk
Created June 29, 2016 18:22
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 selbyk/ef588f9cbf5f051aca435c91299138ef to your computer and use it in GitHub Desktop.
Save selbyk/ef588f9cbf5f051aca435c91299138ef to your computer and use it in GitHub Desktop.
Find the amount of numbers between two positive integers whose digits sum equals another given positive integer
/**
* Find the amount of numbers between 10 and 1000 whose digits sum equals 9
*/
// lodash gives us lots of useful magic functions for arrays, objects, etc
const _ = require('lodash');
// set up our variables
let start = 10, end = 1000;
let digitTotal = 9;
let counter = 0;
// loop through intergers between start and finish
for(let i = start + 1; i < end; ++i) {
// convert current number to string to make getting digits much easier
let currentNumber = i.toString();
// turn into array of digits and convert them to integers
let digits = currentNumber
.split('')
.map((x) => { return parseInt(x); });
// print the current number
// console.log(currentNumber);
// magic summing of numbers
let sum = _.reduce(digits,
(memo, num) => {
return memo + num;
},
0);
// if the digits are equal to our target
// increase counter by one, display counter,
// and display the current number
if( sum === digitTotal ) {
++counter;
console.log(counter + ": " + currentNumber);
}
}
console.log("A total of " + counter + " integers between " + start + " and " + end + ' whose digits add up to ' + digitTotal);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment