본문 바로가기
알고리즘/Codewars

[Codewars] Find the divisors! (7 kyu) / JavaScript

by fluss 2023. 1. 13.

https://www.codewars.com/kata/544aed4c4a30184e960010f4

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

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<Vec<u32>, String> in Rust).

Example:

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

코드

function divisors(integer) {
  const result = [];
  const range = Math.floor(integer / 2);
  for(let i = 2; i <= range; i++){
    if(integer % i == 0) result.push(i);
  }
  return result.length ? result : `${integer} is prime`;
};

댓글