๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm/์ธํ”„๋Ÿฐ(inflearn)

[ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(JavaScript) ] section04 - 2 - ๋’ค์ง‘์€ ์†Œ์ˆ˜

by YWTechIT 2021. 8. 22.
728x90

๐Ÿ“ section04 - 2 - ๋’ค์ง‘์€ ์†Œ์ˆ˜(bruteForce)

์ž์—ฐ์ˆ˜๋ฅผ ๋’ค์ง‘์„ ๋•Œ stringํ˜•์„ ์‚ฌ์šฉํ•˜๋Š” ๋Œ€์‹  numberํ˜• ๊ทธ๋Œ€๋กœ ๋’ค์ง‘๋Š” ๋ฐฉ๋ฒ•์„ ์•Œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์†Œ์ˆ˜๋ฅผ ํŒ๋ณ„ํ•  ๋•Œ๋Š” ๋ฐ˜๋ณต๋ฌธ์˜ ๋ฒ”์œ„๋ฅผ i <=Math.floor(n**0.5)๊นŒ์ง€๋งŒ ์„ค์ •ํ•ด์ฃผ๋ฉด ๋” ์ ์€ ์‹œ๊ฐ„์— ์†Œ์ˆ˜๋ฅผ ํŒ๋ณ„ํ•  ์ˆ˜ ์žˆ๋‹ค. ์ฝ”๋“œ์˜ ๊ฐ€๋…์„ฑ์„ ๋†’์ด๊ธฐ ์œ„ํ•ด ์ž์—ฐ์ˆ˜๋ฅผ ๋’ค์ง‘๋Š” ๋กœ์ง๊ณผ ์†Œ์ˆ˜๋ฅผ ํŒ๋ณ„ํ•˜๋Š” ๋กœ์ง์„ ๋‚˜๋ˆ ์„œ ํ•˜๋Š” ํŽธ๋„ ์ข‹๋‹ค. ์†Œ์ˆ˜ ํŒ๋ณ„ ๋ฌธ์ œ๋Š” ์ด์ „์—๋„ ์ข…์ข… ํ’€์—ˆ๋‹ค.

// ๋‚˜์˜ ์ฝ”๋“œ
let n = 9;
let arr = [32, 55, 62, 20, 250, 370, 200, 30, 100];

console.log(solution(n, arr));

function solution(n, arr) {
  let answer = "";

  for (let number of arr) {
    let sum = 0;
    let flag = true;

    do {
      sum = sum * 10 + number % 10;
      number = Math.floor(number / 10);
    } while (number > 1);

    if (sum > 1) {
      for (let i = 2; i <= Math.floor(sum ** 0.5); i++) {
        if (sum % i === 0) {
          flag = false;
          break;
        }
      }
      if (flag) answer += `${sum} `;
    }
  }
  return answer.slice(0, -1);
}
728x90
// ๊ฐ•์‚ฌ๋‹˜ ์ฝ”๋“œ
let n = 9;
let arr = [32, 55, 62, 20, 250, 370, 200, 30, 100];

console.log(solution(n, arr));

function isPrime(n) {
  if (n < 2) return false;

  for (let i = 2; i <= Math.floor(n ** 0.5); i++) {
    if (n % i === 0) return false;
  }
  return true;
}

function solution(n, arr) {
  let ans = "";

  for (let number of arr) {
    let sum = 0;
    do {
      sum = sum * 10 + (number % 10);
      number = Math.floor(number / 10);
    } while (number > 1);

    if (isPrime(sum)) ans += `${sum} `;
  }

  return ans.slice(0, -1);
}
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€