1.문제
Given two positive integers a and b, return the number of common factors of a and b.
An integer x is a common factor of a and b if x divides both a and b.
두 양수 a,b가 주어질 때 a,b의 공통약수의 갯수를 구하는 문제이다.
Example 1
Input: a = 12, b = 6
Output: 4
Explanation: The common factors of 12 and 6 are 1, 2, 3, 6.
Example 2
Input: a = 25, b = 30
Output: 2
Explanation: The common factors of 25 and 30 are 1, 5.
Constraints:
2.풀이
- a,b의 공약수는 a,b 보다 클 수 없다
- 1부터 ~ Math.min(a,b) 사이의 수를 순회하면서 a,b 를 나누었을 때 나머지가 0이라면 count + 1
/**
* @param {number} a
* @param {number} b
* @return {number}
*/
const commonFactors = function (a, b) {
const minimum = Math.min(a, b);
let count = 0;
for (let i = 1; i <= minimum; i++) {
if (a % i === 0 && b % i === 0) {
// i 가 a , b 를 나누었을 때 둘다 나머지가 0이라면 공통 약수이다
count++;
}
}
return count;
};
3.결과
