Codility Lesson11. Sieve of Eratosthenes - ☆ CountNonDivisible [Medium]

세나정·2023년 4월 26일
0
post-thumbnail

Tasks

https://app.codility.com/programmers/lessons/11-sieve_of_eratosthenes/

function solution(A) {
    const n = A.length;

    // i 번째 인덱스 === A[i]의 개수
    const countArray = Array((n * 2 + 1)).fill(0);

    for (let i = 0; i < n; i++) {
        countArray[A[i]] += 1;
    }

    let result = [];
    for (let i = 0; i < n; i++) {
        const now = A[i];

        let count = 0;
        for (let j = 1; j ** 2 <= now; j++) {
            if (now % j === 0) {
                count += countArray[j];

                // now / j === j 일 경우 두번 계산되기 때문에 한번 걸러준다.
                if(now / j !== j) {
                    count += countArray[now / j];
                }
                
            }
        }

        result.push(n - count);
    }

    return result;
}
profile
기록, 꺼내 쓸 수 있는 즐거움

0개의 댓글