DEV Community

Cesar Del rio
Cesar Del rio

Posted on • Updated on

#32 - Find the divisors! CodeWars Kata (7 kyu)

Instructions

Create a function named divisors/Divisors that takes an integer n > 1 and returns an array with all of the integer's divisors(except for 1 and the number itself), from smallest to largest. If the number is prime return the string '(integer) is prime' (null in C#) (use Either String a in Haskell and Result , String> in Rust).

Example:

divisors(12); // should return [2,3,4,6]
divisors(25); // should return [5]
divisors(13); // should return "13 is prime"


My solution:

function divisors(integer) {
  let r = []
  for(let i = 2; i<integer; i++){
    if(integer%i == 0) r.push(i)
  }
  let res = r.length !== 0 ? r : `${integer} is prime`
  return res
}
Enter fullscreen mode Exit fullscreen mode

Explanation

Firs I decalrated the variable "r" tha contains an empty array.

let r = []

After that I started a loop that will iterate from 2 to the integer value, in every iteration I'll check if "i" is divisible by the integer, and if it is I'll push it to the "r" array.

for(let i = 2; i<integer; i++){
if(integer%i == 0) r.push(i)
}

After that I'll check if the length of array isn't 0, it'll return the array, and if it is 0, it'll return ${integer} is prime, and at the end I'll just return this result.

let res = r.length !== 0 ? r : ${integer} is prime
return res


What do you think about this solution? 👇🤔

My Github
My twitter
Solve this Kata

Top comments (0)