5178. 四因数

给你一个整数数组 nums,请你返回该数组中恰有四个因数的这些整数的各因数之和。

如果数组中不存在满足题意的整数,则返回 0 。

示例:

输入:nums = [21,4,7]
输出:32
解释:
21 有 4 个因数:1, 3, 7, 21
4 有 3 个因数:1, 2, 4
7 有 2 个因数:1, 7
答案仅为 21 的所有因数的和。
 

提示:

1 <= nums.length <= 10^4
1 <= nums[i] <= 10^5

1.直接枚举每一个数的因数的话 10^9,其实只要枚举到sqrt(nums[i])即可,10^6

import math
class Solution:
    def sumFourDivisors(self, nums: List[int]) -> int:
        res = 0
        for i in range(len(nums)):
            count = 0
            s = 0
            for j in range(1,int(math.sqrt(nums[i]))+1):
                if nums[i]%j==0:
                    other = nums[i]//j
                    if other!=j:
                        count+=2
                        s +=(other+j)
                    else:
                        count+=1
                        s+=j
            if count==4:
                res+=s
        return res
发布了216 篇原创文章 · 获赞 17 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_36328915/article/details/105033744