0

Adding to an array when the remainder of the separation is equal to 0

Hello. For some reason, only 15 is prime is constantly issued, although I seem to write everything correctly in the conditions that the array would be replenished with values :( function divisors(integer) { const items = []; for(i=2; i<=integer; i++) { const item = items[i]; if(integer%i == 0) { items.push[i]; } else { return `${integer} is prime`; } } }; console.log(divisors(15));

6th Apr 2021, 12:46 PM
Bomko Aleksey 👨‍💻
Bomko Aleksey 👨‍💻 - avatar
6 Antworten
+ 1
function divisors(integer) { const items = []; for (i = 2; i < integer; i++) { if (integer % i === 0) { items.push(i); } } return items.length ? items : `${integer} is prime`; } console.log(divisors(8));
6th Apr 2021, 9:14 PM
CamelBeatsSnake
CamelBeatsSnake - avatar
+ 1
Bomko Aleksey 👨‍💻 you'll probably want to handle negative numbers too but it depends on your needs/the task.
6th Apr 2021, 9:15 PM
CamelBeatsSnake
CamelBeatsSnake - avatar
+ 1
CamelBeatsSnake thanks :) You don't need to work with negative ones)
9th Apr 2021, 7:29 PM
Bomko Aleksey 👨‍💻
Bomko Aleksey 👨‍💻 - avatar
0
Hmm, prime numbers can be divided by itself and 1 only, so in your "for" loop, you should make it i<integer, cuz you want to check if there are any other divisor(not including 1 and "integer"). So, if(integer%i==0){ return '${integer} is not prime'; } And after your for loop ends, you can return what you wrote in your code
6th Apr 2021, 2:48 PM
Michal Doruch
0
Michal Doruch it is not clear how to add to the array the values that we get in the absence of a remainder from division: (integer% i == 0). Example 15 - you need to get an array with 3 and 5, but I tried everything and nothing happened.
6th Apr 2021, 8:21 PM
Bomko Aleksey 👨‍💻
Bomko Aleksey 👨‍💻 - avatar
0
Why would you save them in array, when you are not using it anywhere? I do not know how exactly JavaScript works, but probably if you want to use these values outside the function, it has to be defined as global, otherwise these can be used in scope of function only. If you don't want to use global variables, you can pass array reference. (cuz from what I know, there are no pointers) If you do not need to save values, just print them inside that 'if' statement
6th Apr 2021, 8:56 PM
Michal Doruch