Rosetta Code: Factors of an integer Javascript issue

I really thought I would solve this problem easily because it seemed so simple. Add the factors of a number to an array(https://www.freecodecamp.org/learn/coding-interview-prep/rosetta-code/factors-of-an-integer) .I came up with the algorithm for this problem ,but everytime I run it in a console, it returns an empty array. What gives? Here is the link to my code.

It all lays in your math comparison:

if(i%num==0)

By definition, i <num so the reminder will never be 0, but more likely the value of i, for example

i = 2, num = 6, 2%6 = 2 (and not 0 as you expected)

Without giving you the answer, you should be able now to understand where the problem is.
Hope this helps :slight_smile:

1 Like

Everything else is fine but I need to change what is inside my comparison statement?

I see what you mean. like any i less than number , its going to return that number i , just like in modular arithmetic

Yep, in the example I gave you

i = 2, num =6

 2 / 6 = 0 with a reminder of 2

And that’s why i%num ===0 is not the operation you are probably thinking of.
Close, but not the same :wink:

1 Like

The real question is what’s the smallest number of comparisons that you need?

Am I closer to the solution? https://codepen.io/noblegas/pen/VwYzNBx

Can you explain why you made your latest changes? What is your algorithm?

My algorithm is to iterate up until the number that is given as an argument thats passed in my function, and check to see if the latest number that was iterated is a factor of the number thats given as an argument. If it is , then I add it to the array that I initially declared as empty using the push method.

What is the purpose of num/=i;? What part of the algorithm is it?

I ask, because you end up changing the value of num which is part of your for loop condition.

       if(num%i==0){
          num/=i;
           factorsArray.push(num)
        }

What are the reasons for num/=i?
As this introduces the side effect of changing num while running, you should be careful about that.

Wow, turns out I needed to substract 1 from num while iterating.
function factors(num){

let factorsArray=[];


for(let i=1; i<num-1;i++){

   
   if(num%i==0){
       

       factorsArray.unshift(i)
    }
       
   }

  
return factorsArray;

}

That made a BIG difference in the output of my function

Perfection:

function factors(num){

let factorsArray=[];


for(let i=1; i<=num;i++){

   
   if(num%i==0){
       

       factorsArray.push(i)
    }
       
   }

  
return factorsArray;

}

Glad you could solve it :clap:

1 Like