I was writing a program in JavaScript that calculates the number of 6-digit numbers the sum of whose first 3 digits is equal to the sum of the last 3 digits. So I wrote two different solutions to the problem although only one returns the correct answer.
Also I wrote a function sumOfDigits()
which simply calculates the sum of digits of the number passed to it. This function is not written here but it works correct.
function count1() {
total=0;
for (i = 100000; i <= 999999; i+=1) {
part = i % 1000;
if ((sumOfDigits(i-part)) == ((sumOfDigits(part)))) {
total+=1;
}
} return total;
}
function count2() {
array = [];
for (i = 100000; i <= 999999; i+=1) {
part = i % 1000;
if ((sumOfDigits(i-part)) == ((sumOfDigits(part)))) {
array.push(i);
}
} return array;
}
The count1()
function does not work correctly and returns 28 as the answer while the count2()
function which returns an array returns an array of length 50412 which is the correct answer. Can somebody please tell me why the first function does not work correctly.
A screenshot of the count1
function in action.