* [프로그래머스] 소수 찾기 - JavaScript

📌 문제

https://programmers.co.kr/learn/courses/30/lessons/42839



📌 풀이

function solution(numbers) {
  const arr = numbers.split("");
  const answer = new Set();

  getPrimeNumber(arr, "");

  function getPrimeNumber(numbersArr, currentNumber) {
    if (numbersArr.length) {
      for (let i = 0; i < numbersArr.length; i++) {
        const temp = [...numbersArr];
        temp.splice(i, 1);

        if (isPrime(parseInt(currentNumber + numbersArr[i]))) {
          answer.add(parseInt(currentNumber + numbersArr[i]))
        }

        getPrimeNumber(temp, currentNumber + numbersArr[i])
      }
    }
  }

  function isPrime(n) {
    if (n < 2) return false;
    for (let i = 2; i <= Math.sqrt(n); i++) {
      if (n % i === 0) return false;
    }
    return true;
  }

  return answer.size;
}

좋은 웹페이지 즐겨찾기