-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalgorithm13.html
63 lines (42 loc) · 1.08 KB
/
algorithm13.html
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<!DOCTYPE html>
<html>
<body>
<script>
//https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes
//Sum All Primes : A prime number is a whole number greater than 1 with exactly two divisors: 1 and itself.
//Return the sum of all prime numbers that are less than or equal to num.
function generateSequence(num) {
var result = [];
for (var i=1; i<=num; i++) {
result.push(i);
}
return result;
}
function isDivisible(num, candidate) {
return num%candidate === 0;
}
function isPrime(num) {
if (num == 1) {
return false;
}
for (var i=2; i<num; i++) {
if (isDivisible(num, i)) {
return false;
}
}
return true;
}
function sumPrimes(num) {
var arr = generateSequence(num);
var primeArr = arr.filter(isPrime);
//sum all the numbers
return primeArr.reduce((a,b)=> (a+b));
}
//tests
console.log(isPrime(1));
console.log(isPrime(11));
console.log(sumPrimes(10));
console.log(sumPrimes(977));
</script>
</body>
</html>