* fix(guide) add stubs and correct file path misspellings and pr… (#36528) * fix: corrected file path to match curriculum * fix: renamed to newer challenge name * fix: added solutions to articles from challenge files * fix: added missing .english to file name * fix: added missing title to guide article * fix: correct solution for guide article * fix: replaced stub with hint * fix: added space in Hint headers * fix: added solution to guide article * fix: added solution to guide article * test: replaced stub with hint and solution * fix: add Problem number: to title * fix: changed generatorexponential to correct name * fix: renamed knight's tour to knights-tour * fix: updated guide article
1.3 KiB
1.3 KiB
title
title |
---|
Problem 10: Summation of primes |
Problem 10: Summation of primes
Problem Explanation
- In this challenge we need to find sum of all prime numbers up to
n
. - Example:
- If
n = 10
then prime numbers before it are2, 3, 5, 7
and their sum is17
.
- If
- We've used Sieve of Eratosthenes algorithm to find prime numbers in the below solution.
Solutions
Solution 1 (Click to Show/Hide)
function primeSummation(n) {
// Initializing the array and sum which hold all prime numbers and the total sum, respectively
let nums = []
let sum = 0;
// Upperbound of `n`
const upperBound = Math.ceil(Math.sqrt(n));
// Making an array of `n` numbers
for (let i = 0; i < n; i++){
nums.push(i);
}
nums[1] = 0;
// Looping until the upperbound
for (let i = 2; i <= upperBound; i++){
// Skipping if the number is already 0
if (nums[i] !== 0){
// Explcitly marking all multiples of `i` 0
for (let j = i*i; j < n; j += i){
if (nums[j] % i == 0) {
nums[j] = 0;
}
}
}
}
// Sum and return all values in the array up to `n`
for (let i = 0; i < n; i++){
sum += nums[i];
}
return sum;
}
Relevant Links
- Sieve of Eratosthenes Wikipedia