Reputation: 337
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.
Upvotes: 3
Views: 114
Reputation: 122888
I think you could reconsider your code. Here is a simpler and faster approach (<500ms in nodejs, faster because it's all numbers, i.e. no conversions):
//helper: sum of digits in number [n]
function sumOfDigits(n){
if (!(n^0) || n<10) {return n;}
var sum = 0;
while (n>=10) {
sum += n%10;
n = (n/10)^0;
}
return sum+n;
}
function sumDigitsComparer(num){
return sumOfDigits((num/1000)^0) === sumOfDigits(num%1000);
}
var x = 1000000, n = 0;
while ((x-=1,x>=100000)) { sumDigitsComparer(x) && (n+=1); }
//=> n = 50412
Upvotes: 0
Reputation: 185852
Are you using total
in the implementation of sumOfDigits()
? I'm guessing that both functions are using the same global total
.
You should prefix all local variables with var
on their first use so that they aren't treated as global variables, e.g.:
var total = 0;
EDIT: I just confirmed this. If sumOfDigits()
uses the global total
, count1()
returns 28.
Upvotes: 5
Reputation: 3965
May be total
is a global variable with some value on your solution. Try create another variable for return:
function count1() {
var count = 0;
for (i = 100000; i <= 999999; i+=1) {
part = i % 1000;
if ((sumOfDigits(i-part)) == ((sumOfDigits(part)))) {
count+=1;
}
} return count;
}
Upvotes: 1