HR - Between Two Sets

Goody·2021년 2월 3일
0

알고리즘

목록 보기
25/122

문제

There will be two arrays of integers. Determine all integers that satisfy the following two conditions:

  1. The elements of the first array are all factors of the integer being considered.
  2. The integer being considered is a factor of all elements of the second array.

These numbers are referred to as being between the two arrays.
Determine how many such numbers exist.

  • Example
    a = [2, 6]
    b = [24, 36]

There are two numbers between the arrays: 6 and 12 .

예시

INPUT

2 3
2 4
16 32 96

OUTPUT

3

Explanation
2 and 4 divide evenly into 4, 8, 12 and 16.
4, 8 and 16 divide evenly into 16, 32, 96.

4, 8 and 16 are the only three numbers for which each element of a is a factor and each is a factor of all elements of b.

풀이

  • 배열 b 의 공약수 중, 배열 a 의 원소들을 약수로 갖는 숫자들의 개수를 구하는 문제이다.
  • b 배열 내 원소들의 공약수를 구할 때는 모든 원소가 주어진 수로 나누어 떨어지는 지 검사하면 된다.
  • 위와 동시에 주어진 수를 a 배열 원소들에 대해 나누어 떨어지는 지 검사하면 주어진 수는 b 배열 원소들의 공약수인 동시에 a 배열 원소들을 약수로 갖는 숫자이다.

코드

function getTotalX(a, b) {

    let validCount = 0;

    for (let x = 1; x <= 100; x++) {
        if (b.every(element => (element % x === 0))) {
            if (a.every(element => (x % element === 0))) {
                validCount++;
            }
        }
    }

    return validCount;
}

0개의 댓글