DEV Community

Cesar Del rio
Cesar Del rio

Posted on • Updated on

#35 -(Ready for) Prime Time - CodeWars Kata (5 kyu)

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
}
Enter fullscreen mode Exit fullscreen mode

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? 👇🤔

My Github
My twitter
Solve this Kata

Top comments (0)