John the User - 4 months ago 21

Javascript Question

I'm new to javascript and was trying to find the prime factors of a number, recorded below as 'integer' using a for loop in javascript. I can't seem to get it working and I'm not sure whether it's my javascript or my calculation logic. I tried to add comments so that you can see what I think my program is doing at that time. Correct me if I'm wrong.

Any help will be appreciated. Here's my code:

`//integer is the value for which we are finding prime factors`

var integer = 13195;

var primeArray = [];

//find divisors starting with 2

for (i = 2; i < integer/2; i++) {

if (integer % i == 0) {

//check if divisor is prime

for (var j = 2; j <= i / 2; j++) {

if (i % j == 0) {

isPrime = false;

} else {

isPrime = true;

}

}

//if divisor is prime

if (isPrime == true) {

//divide integer by prime factor & factor store in array primeArray

integer /= i

primeArray.push(i);

}

}

}

for (var k = 0; k < primeArray.length; k++) {

console.log(primeArray[k]);

}

Answer

Here's a working solution:

```
//integer is the value for which we are finding prime factors
var integer = 13195,
primeArray = [],
isPrime;
//find divisors starting with 2
for(i = 2; i <= integer; i++){
if (integer % i==0) {
//check if divisor is prime
for(var j = 2; j <= i/2; j++) {
if(i % j == 0) {
isPrime = false;
} else {
isPrime = true;
}
}
//if divisor is prime
if (isPrime == true) {
//divide integer by prime factor & factor store in array primeArray
integer /= i
primeArray.push(i);
}
}
}
for (var k = 0; k < primeArray.length; k++) {
console.log(primeArray[k]);
}
```

You were very much on the right track. There were a two minor mistakes. The evaluation of `integer - 1`

seemd to be incorrect. I believe the more appropriate evaluation is `<= integer`

in your outer `for`

loop. This is because when you divide your integer below `integer /= i`

, this results in the final integer evaluation to be `29`

. The final prime divsor in this case is also `29`

and as such will need to be evaluated as `<=`

as oppose to `< integer - 1`

.

As for why the final log statment isn't working, there was a simple typo of `primeArray[i]`

as oppose to `primeArray[k]`

.