알고리즘 공부[Javascript]/백준

[백준] 1978번 / 실버4 / 소수 찾기 / Node.js

Kevinkb 2021. 8. 7. 19:27

문제

주어진 수 N개 중에서 소수가 몇 개인지 찾아서 출력하는 프로그램을 작성하시오.

입력

첫 줄에 수의 개수 N이 주어진다. N은 100이하이다. 다음으로 N개의 수가 주어지는데 수는 1,000 이하의 자연수이다.

출력

주어진 수들 중 소수의 개수를 출력한다.

예제 입력

4
1 3 5 7

예제 출력

3

소스 코드

// fs
let [n, arr] = require('fs').readFileSync('/dev/stdin').toString().trim().split('\n');
arr = arr.split(' ').map(Number);

let count = 0;

for(let i = 0; i < arr.length; i++) {
    let bol = true;
    if (arr[i] === 1) {
        bol = false;
    }
    for(let j = 2; j <= Math.sqrt(arr[i]); j++) {
        if (arr[i] % j === 0) {
            bol = false;
        }
    }
    if (bol) {
        count++;
    }
}

console.log(count);

// readline
const rl = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
});

let input = [];
let count = 0;

rl.on('line', function(line) {
      input.push(line);
}).on('close', () => {
    let [n, arr] = input;
    arr = arr.split(' ').map(Number);

    for(let i = 0; i < arr.length; i++) {
        let bol = true;
        if (arr[i] === 1) {
            bol = false;
        }
        for(let j = 2; j <= Math.sqrt(arr[i]); j++) {
            if (arr[i] % j === 0) {
                bol = false;
            }
        }
        if (bol) {
            count++;
        }
    }

    console.log(count);
    process.exit();
})