#35 -(Ready for) Prime Time - CodeWars Kata (5 kyu)
Cesar Del rio
Posted on February 18, 2022
Instructions
We need prime numbers and we need them now!
Write a method that takes a maximum bound and returns all primes up to and including the maximum bound.
Example
11 => [2, 3, 5, 7, 11]
My solution:
function prime(num) {
function isPrime(n) {
if(n == 2) return true
for (let i = 2; i < n; i++) {
if (n % i == 0) return false
}
return true
}
var r = []
for(let i = 2; i <= num; i++){
if(isPrime(i)) r.push(i)
}
return r
}
Explanation
First I did a function that returned if a number is a prime, using a loop that iterates if the number that is being checked can be divided by another number before it, if it can be divided it means that the number isn't prime, so it returns false, but if it can't be divided it returns true.
function isPrime(n) {
if(n == 2) return true
for (let i = 2; i < n; i++) {
if (n % i == 0) return false
}
return true
}
After that I did a variable "r" that contained an empty array and in this array I'll store the last result.
var r = []
Then I used a for loop that iterated all the numbers from 2 to the number that the function passes as a parameter, and in every oneof the iterations I checked if the number being iterated is prime, and if it is prime I just pushed it to the "r" array.
for(let i = 2; i <= num; i++){
if(isPrime(i)) r.push(i)
}
Then I returned the "r" array
return r
What do you think about this solution? 👇🤔
Posted on February 18, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.