Skip to content

1390. Four Divisors

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  int sumFourDivisors(vector<int>& nums) {
    int ans = 0;

    for (int num : nums) {
      int divisor = 0;
      for (int i = 2; i * i <= num; ++i)
        if (num % i == 0) {
          if (divisor == 0)
            divisor = i;
          else {
            divisor = 0;
            break;
          }
        }
      if (divisor > 0 && divisor * divisor < num)
        ans += 1 + num + divisor + num / divisor;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public int sumFourDivisors(int[] nums) {
    int ans = 0;

    for (int num : nums) {
      int divisor = 0;
      for (int i = 2; i * i <= num; ++i)
        if (num % i == 0) {
          if (divisor == 0)
            divisor = i;
          else {
            divisor = 0;
            break;
          }
        }
      if (divisor > 0 && divisor * divisor < num)
        ans += 1 + num + divisor + num / divisor;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
  def sumFourDivisors(self, nums: List[int]) -> int:
    ans = 0

    for num in nums:
      divisor = 0
      for i in range(2, int(sqrt(num)) + 1):
        if num % i == 0:
          if divisor == 0:
            divisor = i
          else:
            divisor = 0
            break
      if divisor > 0 and divisor * divisor < num:
        ans += 1 + num + divisor + num // divisor

    return ans