Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

153
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!