Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

174
Visualizações
convert the given array to an array of Boolean where Each element is true if the number is a prime number, and false otherwise

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? :/

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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

  1. We check only odd numbers because an element can't be divisible by an even number if it's not already divisible by 2.
  2. We don't need to check ALL the numbers less than "element" - we need to check only numbers from 3 to square root of the element. If you need any additional explanation why - I can give it.
  3. I suggest using "map" instead of creating an array and pushing there - it's more efficient. Also, it protects you from missing "else" and "break" statements - every check immediately finishes when true or false is added to the answers list.

UPD: Added Math.abs function call, so negative numbers will be processed correctly.

about 4 years ago · Juan Pablo Isaza Relatório

0

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;
  } 

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda