Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

156
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda