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?
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)}`);