I need to find out either a number is Prime or not in an array. in the beginning I thought it's easy, but .. :)
First I tried this version :
function primeValues(arr) {
let newArr = []
for( let el of arr) {
if (el <= 2 ) {
newArr.push(true)
}
for (let j=2; j<el; j++) {
if (el%j === 0) {
newArr.push(false)
}
if (el%j !==0 ) {
newArr.push(true)
}
}
}
return newArr;
}
console.log(primeValues([17, 3, 21]));
But every time it goes through for loop, It pushes True or False in my new array :/`
(35) [true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, true, true, true, false, true, true, true, true, true, true, true, true, true, true, true, true, true]
what should I do? :/
function primeValues(arr) {
return arr.map(element => {
const x = Math.abs(element);
if(x <= 2) return true;
if(x % 2 === 0) return false;
for(let i = 3; i <= Math.sqrt(x); i+=2) {
if(x % i === 0) {
return false;
}
}
return true;
});
}
console.log(primeValues([7,9,11,13,-21,2,54]));
I added some optimizations to the code
true or false is added to the answers list.UPD: Added Math.abs function call, so negative numbers will be processed correctly.
this way...
console.log( JSON.stringify( primeValues( [17, 3, 21 ] )))
function primeValues(arr)
{
let result = [], modulo;
for( let el of arr)
{
if (el <= 2 )
result.push(true)
else // this one is missing in your code
{
modulo = 1 // modulo initial assignement must be there
for (let j = 2; j < el; j++) // or (let j=3; j<el; j +=2)
{ // see Alexey Zelenin explanations
modulo = el % j
if (modulo === 0)
{
result.push(false)
break // this other one is missing in your code
}
}
if (modulo !== 0) result.push(true) // test last modulo value
} // outside the loop (and it's scope)
}
return result;
}
But you might prefer to code it like this:
console.log( JSON.stringify( primeValues([ 17, 3, 21 ] )))
function primeValues(arr)
{
let result = []
, isNotPrim
;
for (let el of arr)
{
isNotPrim = false
if (el > 2)
for (let j = 2; j < el; j++)
if (isNotPrim = !(el %j))
break
;
result.push( !isNotPrim )
}
return result;
}