Finding the Sum of All Primes Equal to or Under a Given Number in JavaScript (and Then Again in Ruby)
So, as promised here I am with the answer of how to get the sum of primes under a given number. JS and Ruby have very different ways of managing this, as before I will first approach the JS solution, then will go into the much swifter Ruby version.
So lets get into the JS shall we!
Our task is as follows, For a given number (num) we must find the sum of all the Prime Numbers under or equal to the value of num.
The full JS code is below
function sumPrimes(num) { let primes = []for (let i = 2; i<=num; i++){ if (i == 2){ primes.push(i) } else if( i % 2 !== 0 ){ let prime = true if (prime){ for(let j=2; j<i; j++){ if (i % j === 0 ){ prime = false } } } if(prime){ primes.push(i) } } }const reducer = (accumulator, currentValue) => accumulator + currentValue;let total = primes.reduce(reducer)return total;}
Oof, look at all those nested brackets. However they are important if we want to make sure we are making a good old array of primes.
Let’s go through this step by step shall we.
Firstly we create a nice empty array to be ready to get filled with our Primes
let primes = []
Now is the part where we start doing some nested for loops, the reason behind this is we need to make sure that no number we are going to push to the primes array is going to be divisible by anything except itself and 1.
First we check if the number is 2, which is we are starting counting at 2 it should hopefully be. If so we push it to the array
if (i == 2){primes.push(i)}
You could alternately just start the primes array at 2 and get rid of this step all together, I however wanted to keep it in for a sense of completeness.
Anyway now lets get to the real core of the function. Checking if the rest of the values are primes.
else if( i % 2 !== 0 ){ let prime = true if (prime){ for(let j=2; j<i; j++){ if (i % j === 0 ){ prime = false } } }
}
We first check to see if the current value for our ‘i’ is divisible by 2, as if it fails this very first check, it is definitely not a prime.
If the number is not divisible by 2 then we move on and set a variable to ‘true’ (call it whatever you like, but I just called it prime).
We set up a secondary for loop here, to iterate through all the numbers lower than our current value for ‘i’ and then checking if when ‘i’ is divided by these numbers if there is any remainder.
If the remainder at any point is 0, then our value for ‘i’ is not a prime and we set our prime variable to false.
As soon as our prime variable is set to false the ‘for loop’ stops due to the if statement checking to see if prime remains true.
if (prime)
This just saves time, as soon as prime is set to false the loop stops as the number is definitely no longer a prime and no point in keeping on going!
Then if prime gets through all this testing whilst remaining true we push ‘i’ to the array.
if(prime){ primes.push(i)}
‘i’ will continue to increment for all the numbers until it equals our given num value.
Now we have our wonderful array of primes!
To now get the sum of these we just now need to create out reducer constant and pass it and the array in into the glorious reduce method provided to us by JS.
const reducer = (accumulator, currentValue) => accumulator + currentValue;let total = primes.reduce(reducer)return total;
This gives us our final total which we can return! Victory is ours!
Now have a break, have a walk about, stretch those aching legs. I’ll wait here
Now onto the Ruby method for completing the same task:
require 'Prime'
def sum_primes(num) Prime.each(num).sumend
So thats quite pleasant! First we need to require ‘Prime’, this then allows us to access Prime.each(num) returns an object made of all the Prime numbers equal to or under the given ‘num’, then adding .sum to the end tallys them all and with Ruby methods having implicit returns we don’t even need to tell it to return! Gloriously concise!
I hope this has been a helpful journey! I shall do another next week, if anyone has any suggestions of challenges they want looking at I can give them ago and report back!
Keep calm and code on.
Dan