1390. Four Divisors (M)

Four Divisors (M)

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 = [21,4,7]
Output: 32
Explanation:
21 has 4 divisors: 1, 3, 7, 21
4 has 3 divisors: 1, 2, 4
7 has 2 divisors: 1, 7
The answer is the sum of divisors of 21 only.

Constraints:

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

题意

返回所有因数个数为4的数的因数之和。

思路

因数不重复,所以如果一个数是完全平方数,则它的因数个数一定是奇数,可直接排除。其它数因数都成对出现,当找到第三对因数时可直接跳过该数。


代码实现

class Solution {
    public int sumFourDivisors(int[] nums) {
        int ans = 0;
        
        for (int num : nums) {
            int sqrt = (int) Math.sqrt(num);
            // 完全平方数直接跳过
            if (sqrt * sqrt == num) {
                continue;
            }
            int sum = 1 + num;
            int count = 1;
            for (int i = 2; i <= sqrt; i++) {
                if (num % i == 0) {
                    count++;
                    sum += i + sum / i;
                    if (count > 2) {
                        break;
                    }
                }
            }
            // 因数对数恰好为2时才计入答案
            if (count == 2) {
                ans += sum;
            }
        }
        
        return ans;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值