0

I'm trying to make a factor calculator. You input a number, and it finds out the factors of that number. If you divide the original number by its factor you get zero, and I'm trying to implement that here so that when it returns with '0' it gets pushed to an array and that array is printed.

var number = prompt("Number?")
    
var array = []   
    
function modulo(a, b)
    {
    return a % b;
    }
    
 for (counter = 0; counter < number; counter++)  
    {
        var result = modulo(number, counter)
        if (result = 0)
           {
           array.push(counter) 
           }
    }
    
    for (counter = 0; counter < array.length; counter++)
    {
        alert(array[counter])
    }

What happens is the prompt shows up, I input a number, and nothing happens. Can anybody help?

Tschallacka
  • 27,901
  • 14
  • 88
  • 133
rivaltor
  • 1
  • 2
  • Your code contains a lot of whitespace that does not really help readability (as well as the indentation - you should indent everything nested in `{}` as they are blocks that only execute inside it). These things will make your code easier to debug for yourself. (In javascript, the `{` bracket is usually placed directly after the declaration, so `function(){`, simply because it combines things more easily, but I guess that's preference) – somethinghere Apr 01 '16 at 10:57

2 Answers2

2

Here is the problem, you have used = (Assignment operator) instead of == comparison operator

for (counter = 0; counter < number; counter++)
{
    var result = modulo(number, counter)
    if (result == 0) // in your code this is result = 0
    {
        array.push(counter)
    }
}

Working demo


Complete code:

var number = prompt("Number?")
var array = []
function modulo(a, b)
{
    return a % b
}
for (counter = 0; counter < number; counter++)
{
    var result = modulo(number, counter)
    if (result == 0)
    {
        array.push(counter)
    }
}

for (counter = 0; counter < array.length; counter++)
{
    alert(array[counter])
}
Manwal
  • 23,450
  • 12
  • 63
  • 93
2

To check if values are equal, use == and not =:

if (result == 0)
Peter B
  • 22,460
  • 5
  • 32
  • 69
  • 1
    a type check is not needed. modulo returns a number. – Tschallacka Apr 01 '16 at 10:58
  • @MichaelDibbets - you should read JavaScript: The Good Parts. Also see this: http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons – stepanian Apr 01 '16 at 11:03
  • i'm already familiar with that, more than familiar even, but it doesn't mean it has to beused everywhere, especially when learning to code in general is more important to know what the hell a typesafe check is. – Tschallacka Apr 01 '16 at 11:08
  • @MichaelDibbets - I'm not sure I understood your response, but result === 0 is more correct and faster than result == 0 although both would work in this case. It's really not a big deal. – stepanian Apr 01 '16 at 11:21