LeetCode1390.四因数四因数【中】【Python】【数学】问题LeetCode给定一个整数数组nums,返回该数组中恰好有四个因数的整数的因数之和.如果数组中没有这样的整数,则返回0。示例1:输入:nums=[21,4,7]输出:32解释:21有4个因数:1,3,7,214有3个因数:1,2,47有2个除数:1,7答案只是21的除数之和。约束条件:1<=nums.length<=10^41<=nums[i]<=10^5给定一个整数数组nums,请返回数组中恰好有四个因数的这些整数的因数之和。如果数组中没有满足问题意图的整数,则返回0。示例:输入:nums=[21,4,7]输出:32解释:21有4个因子:1,3,7,214有3个因子:1,2,47有2个因子:1,7答案很简单21的所有因数之和。Tip:1<=nums.length<=10^41<=nums[i]<=10^5思路数学暴力计算每个数的因数个数。如果满足四个,则添加这些因素。注:因子不能重复。时间复杂度:O(n*max(int(sqrt(x)),4)),n为nums个数。空间复杂度:O(1)Python3代码fromtypingimportListclassSolution:defsumFourDivisors(self,nums:List[int])->int:sum=0forxinnums:ifx==1orx==2orx==3:continuenum=2temp=[1,x]#计算因数whilenum**2<=x:#用num^2<=x比num<=sqrt(x)好iflen(temp)>4:breakifnotx%num:ifnumnotintemp:temp.append(num)ifint(x/num)notintemp:temp.append(int(x/num))num+=1#复制代码print(temp)iflen(temp)==4:for_intemp:#print(_)sum+=_returnint(sum)GitHub链接Python
