Notice
Recent Posts
Recent Comments
Link
ยซ   2024/11   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
Archives
Today
Total
๊ด€๋ฆฌ ๋ฉ”๋‰ด

Lennon FE

[๋ฐฑ์ค€ 9020๋ฒˆ] ๊ณจ๋“œ๋ฐ”ํ์˜ ์ถ”์ธก - ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(nodejs) ๋ณธ๋ฌธ

๐Ÿ”ฅ Algorithm/Baekjoon

[๋ฐฑ์ค€ 9020๋ฒˆ] ๊ณจ๋“œ๋ฐ”ํ์˜ ์ถ”์ธก - ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(nodejs)

Lennon 2022. 1. 18. 18:43
728x90
๋ฐ˜์‘ํ˜•

https://www.acmicpc.net/problem/9020

 

9020๋ฒˆ: ๊ณจ๋“œ๋ฐ”ํ์˜ ์ถ”์ธก

1๋ณด๋‹ค ํฐ ์ž์—ฐ์ˆ˜ ์ค‘์—์„œ  1๊ณผ ์ž๊ธฐ ์ž์‹ ์„ ์ œ์™ธํ•œ ์•ฝ์ˆ˜๊ฐ€ ์—†๋Š” ์ž์—ฐ์ˆ˜๋ฅผ ์†Œ์ˆ˜๋ผ๊ณ  ํ•œ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, 5๋Š” 1๊ณผ 5๋ฅผ ์ œ์™ธํ•œ ์•ฝ์ˆ˜๊ฐ€ ์—†๊ธฐ ๋•Œ๋ฌธ์— ์†Œ์ˆ˜์ด๋‹ค. ํ•˜์ง€๋งŒ, 6์€ 6 = 2 × 3 ์ด๊ธฐ ๋•Œ๋ฌธ์— ์†Œ์ˆ˜๊ฐ€ ์•„

www.acmicpc.net

const fs = require('fs');
let input = fs
  .readFileSync('dev/stdin')
  .toString()
  .trim()
  .split('\n')
  .map((v) => +v);
input.shift();

const isPrime = (num) => {
  if (num === 1) return false;

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

const primeArr = [];

for (let i = 2; i <= 10000; i++) {
  if (isPrime(i)) {
    primeArr.push(i);
  }
}

input.filter((v) => {
  if (primeArr.includes(v / 2)) {
    console.log(`${v / 2} ${v / 2}`);
  } else {
    const arr = [];
    for (let i = 0; i < primeArr.length; i++) {
      for (let j = i + 1; j < primeArr.length; j++) {
        if (primeArr[i] + primeArr[j] === v) {
          arr.push([primeArr[i], primeArr[j]]);
          break;
        }
        if (primeArr[i] > v) {
          break;
        }
      }
    }
    arr.sort((a, b) => {
      const aValue = a[1] - a[0];
      const bValue = b[1] - b[0];

      return aValue - bValue;
    });
    console.log(`${arr[0][0]} ${arr[0][1]}`);
  }
});

์†Œ์ˆ˜ ํŒ๋ณ„ ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค๊ณ  10000์ดํ•˜์˜ ์†Œ์ˆ˜๋ฅผ primeArr์— pushํ•œ๋‹ค.

 

๊ทธ ํ›„ 10000์ดํ•˜์˜ ์ง์ˆ˜ ์ž…๋ ฅ๊ฐ’์— ๋Œ€ํ•ด ์†Œ์ˆ˜์˜ ํ•ฉ์œผ๋กœ ์ •์˜๋˜๋Š” ๊ฐ’๋“ค์„ arr ๋ฐฐ์—ด์— ๋„ฃ๊ณ  ex) 16 => [3,13], [5,11]

sortํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•ด ๊ฐ’์˜ ์ฐจ์ด๊ฐ€ ๊ฐ€์žฅ ์ž‘์€ ๊ฒƒ๋“ค๋กœ ์ •๋ ฌํ•œ ํ›„ 0๋ฒˆ์งธ ์ธ๋ฑ์Šค๋ฅผ ์ถœ๋ ฅํ•˜๋ฉด ๋œ๋‹ค. 

728x90
๋ฐ˜์‘ํ˜•
Comments