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

158
Visualizações
how to find sum of prime numbers in a fibonacci series in javascript?

This is the code i tried to do

function sumFibs(num) {
  let a=1,b=1,c=0,sum=2,count=0;
  while(b<=num){
    c=a+b
    a=b
    b=c
    for(let i=1;i<=c;i++){
      if(c%i===0){
        count++
      }
    }
    if(count===2){
      sum+=c
    }
  }
  return sum
}
console.log(sumFibs(6))

Can someone help me understand how to solve this?

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

0

Make a function for each step.

/**
 * Calculates the Fibonacci sequence up to a given number of times
 * @param   {Number} num Amount of numbers to return
 * @return  {Array[]} An array of numbers
 */
function fibonacci(num) {
  let a = 1,
    b = 0,
    f = [],
    temp;
  while (num > 0) {
    temp = a;
    a = a + b;
    b = temp;
    f.push(b);
    num--;
  }
  return f;
};

/**
 * Calculates the a given number and determines if it is a prime.
 * @param   {Number} int An integer
 * @return  {Boolean} True if int is a prime
 */
function prime(int) {
  if (int < 2) return false;
  for (let i = 2; i <= Math.sqrt(int); i++) {
    if (int % i == 0) return false;
  }
  return true;
};
/**
 * Calls fibonacci(n) then .filter() each number and returns an array of primes and the sum of the primes is the return of .reduce()
 * @param   {Number} num Amount of numbers to get from Fibocanni sequence
 * @return  {Number} A sum of all primes
 */
function fibPrmSum(num) {
  let fib = fibonacci(num);
  console.log(`Fibonacci: ${fib}`);
  let prm = fib.filter(f => prime(f));
  console.log(`Prime: ${prm}`);
  return prm.reduce((sum, now) => sum + now, 0);
};

console.log(`Sum of all primes in the first 6 numbers of the Fibonacci sequence is ${fibPrmSum(6)}`);

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