본문 바로가기

PS/릿코드

[릿코드 1390] Four Divisors (파이썬/python)

728x90

https://leetcode.com/problems/four-divisors/

 

Four Divisors - LeetCode

Can you solve this real interview question? Four Divisors - Given an integer array nums, return the sum of divisors of the integers in that array that have exactly four divisors. If there is no such integer in the array, return 0.   Example 1: Input: nums

leetcode.com

 

약수를 구할때 어짜피 제곱근 까지만 구하면 알아서 짝이 있을거라는 가정하에 계산하면됐습니다.

소수랑 비슷한느낌

 

from typing import List


class Solution:
    def sumFourDivisors(self, nums: List[int]) -> int:
        answer = 0

        for num in nums:
            answer += self.get_divisor_sum_when_divisor_cnt_4(num)

        return answer

    def get_divisor_sum_when_divisor_cnt_4(self, x: int) -> int:
        divisor_set = set()
        total_sum = 0

        for i in range(1, int(x ** (1 / 2)) + 1):
            if x % i == 0:
                divisor_set.add(i)

        if len(divisor_set) == 2:
            for i in divisor_set:
                if i * i == x:
                    return 0
                else:
                    total_sum += i
                    total_sum += x / i

        return int(total_sum)
728x90