Sum Primes

VonRickroll
301 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

The goal today is to write a function that returns the sum of all prime numbers up to a limit. We will do this in two steps: first we're going to write an isPrime function that checks wether or not a number is prime, and then the actual sumPrimes function.

Check if a number is prime

Write an isPrime function that takes a number as parameter and returns true if this number is prime, false if it isn't.

Reminder: A prime number:

  • Can only be divided by 1 and itself
  • Is greater than 1
Write the isPrime function
1
2
3
4
5
6
7
8
9
10
11
12
13
function isPrime (number) {
return false;
// For demo purpose:
/*
var start = 2;
while (start <= Math.sqrt(number)) {
if (number % start++ < 1) return false;
}
return number > 1;
*/
}
module.exports = isPrime;
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Sum all primes

Write a sumPrimes function to sum all prime numbers up to the parameter limit included. Copy you isPrime function from the last assignment to make use of it here.

Write the sumPrimes function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function isPrime (number) {
return false;
// For demo purposes:
/*
var start = 2;
while (start <= Math.sqrt(number)) {
if (number % start++ < 1) return false;
}
return number > 1;
*/
}
function sumPrimes (limit) {
// Return the sum of all prime numbers from 2 to `limit`
return 0;
// For demo purposes:
/*
var s=0;
for(var i=2; i<=limit; i++) {
s+=isPrime(i)?i:0;
}
return s;
*/
}
module.exports = sumPrimes;
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content