Skip to content

Commit fd6a08c

Browse files
committed
Complete sum all primes algorithm
1 parent d42f219 commit fd6a08c

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

src/fcc-intermediate-algorithms/fcc-intermediate-algorithms.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ From the Freecodecamp Javascript Certification Intermediate Algorithms module
1616
- [Sorted Union](#sorted-union)
1717
- [Convert HTML Entities](#convert-html-entities)
1818
- [Sum All Odd Fibonacci Numbers](#sum-all-odd-ficonacci-numbers)
19+
- [Sum All Primes](#sum-all-primes)
1920

2021
#### Sum All Numbers In a Range
2122

@@ -280,3 +281,29 @@ export function sumFibs(num) {
280281
return numbers.reduce((acc, num) => acc + num);
281282
}
282283
```
284+
285+
#### Sum All Primes
286+
287+
Sum all the prime numbers up to and including the provided number.
288+
289+
A prime number is defined as a number greater than one and having only two divisors, one and itself. For example, 2 is a prime number because it's only divisible by one and two.
290+
291+
The provided number may not be a prime.
292+
293+
```javascript
294+
export function sumPrimes(num) {
295+
const generatePrimes = (upperBound) => {
296+
if (upperBound < 2) {
297+
throw 'Upperbound must be >= 2';
298+
}
299+
let primes = [2]
300+
for (let i = 3; i <= upperBound; i += 2) {
301+
if (primes.find(val => i % val === 0) === undefined) {
302+
primes.push(i);
303+
}
304+
}
305+
return primes;
306+
}
307+
return generatePrimes(num).reduce((acc, val) => acc + val);
308+
}
309+
```
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
export function sumPrimes(num) {
2+
const generatePrimes = (upperBound) => {
3+
if (upperBound < 2) {
4+
throw 'Upperbound must be >= 2';
5+
}
6+
let primes = [2]
7+
for (let i = 3; i <= upperBound; i += 2) {
8+
if (primes.find(val => i % val === 0) === undefined) {
9+
primes.push(i);
10+
}
11+
}
12+
return primes;
13+
}
14+
return generatePrimes(num).reduce((acc, val) => acc + val);
15+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import { sumPrimes } from "../../src/fcc-intermediate-algorithms/sum_all_primes";
2+
3+
test('should sum prime numbers', () => {
4+
expect(() => sumPrimes(1)).toThrow('Upperbound must be >= 2')
5+
expect(sumPrimes(10)).toBe(17);
6+
expect(sumPrimes(977)).toBe(73156);
7+
});

0 commit comments

Comments
 (0)