코딩 테스트 및 알고리즘/leetcode for google

leetcode easy : Number of Common Factors

띠리링구 2022. 10. 3. 13:52

https://leetcode.com/problems/number-of-common-factors/

 

두 수의 약수의 개수를 구하는것.

1부터 최대공약수까지 반복문을 돌면서 검사해보면 끝!

class Solution:
    def commonFactors(self, a: int, b: int) -> int:
        answer = 0
        for i in range(1, math.gcd(a,b) + 1 ):
            if a % i == 0 and b % i == 0:
                answer += 1
        return answer

 

한줄코딩

class Solution:
    def commonFactors(self, a: int, b: int) -> int:
        return sum(1 for i in range(1, math.gcd(a,b)+1) if not a % i and not b % i)