Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Help - selfDividingNumbers Algorithm producing all 0's

Greetings Stack Overflow!

First off, this is my first question!

I am trying to solve the selfDividingNumbers algorithm and I ran into this interesting problem. This function is supposed to take a range of numbers to check if they are self dividing.

Self Dividing example:

128 is a self-dividing number because 

128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.

My attempt with Javascript.

/*      
   selfDividingNumbers( 1, 22 );
*/

var selfDividingNumbers = function(left, right) {
    var output = [];
    while(left <= right){
        // convert number into an array of strings, size 1
        var leftString = left.toString().split();

        // initialize digit iterator
        var currentDigit = leftString[0]; 
        
        for(var i = 0; i < leftString.length; i++){
            currentDigit = parseInt(leftString[i])
            console.log( left % currentDigit );
        }
    
        // increment lower bound
        left++;
    }

    return output
};

When comparing the current lower bound to the current digit of the lower bound, left % currentDigit it always produces zero! I figure this is probably a type error but I am unsure of why and would love for someone to point out why!

Would also like to see any other ideas to avoid this problem!

I figured this was a good chance to get a better handle on Javascript considering I am clueless as to why my program is producing this output. Any help would be appreciated! :)

Thanks Stack Overflow!

like image 213
Michael Manteo Avatar asked Mar 12 '18 02:03

Michael Manteo


2 Answers

Calling split() isn't buying you anything. Remove it and you'll get the results you expect. You still have to write the code to populate output though.

like image 139
Joseph Sible-Reinstate Monica Avatar answered Sep 30 '22 04:09

Joseph Sible-Reinstate Monica


The answer by @Joseph may fix your current code, but I think there is a potentially easier way to go about doing this. Consider the following script:

var start = 128;
var num = start;
var sd = true;

while (num > 0) {
    var last = num % 10;
    if (start % last != 0) {
        sd = false;
        break;
    }
    num = Math.floor(num / 10);
}

if (sd) {
    print("Is self dividing");
}
else {
    print("Is NOT self dividing");
}

Demo

To test each digit in the number for its ability to cleanly divide the original number, you can simply use a loop. In each iteration, check num % 10 to get the current digit, and then divide the number by ten. If we never see a digit which can not divide evenly, then the number is not self dividing, otherwise it is.

like image 29
Tim Biegeleisen Avatar answered Sep 30 '22 06:09

Tim Biegeleisen