LeetCode 1390: Four Divisors Solution

Master LeetCode problem 1390 (Four Divisors), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1390. Four Divisors

Medium

Problem Explanation

Explanation:

To solve this problem, we need to iterate through the given array nums, and for each number, check if it has exactly four divisors. We can find the divisors of a number by iterating from 1 up to the square root of the number. If a number i is a divisor, then n/i is also a divisor. By counting the number of divisors for each number, we can identify if a number has exactly four divisors.

Algorithm:

  1. Iterate through the array nums.
  2. For each number, find all its divisors by iterating from 1 to the square root of the number.
  3. Count the number of divisors.
  4. If the count of divisors is exactly four, add the sum of divisors to the result.
  5. Return the final result.

Time Complexity:

  • The time complexity of this algorithm is O(n * sqrt(max(nums))).
  • Here, n is the number of elements in the input array nums.

Space Complexity:

  • The space complexity is O(1) as we are using only a constant amount of extra space.

:

Solution Code

class Solution {
    public int sumFourDivisors(int[] nums) {
        int result = 0;
        for (int num : nums) {
            int sumDivisors = 0;
            int countDivisors = 0;
            for (int i = 1; i <= Math.sqrt(num); i++) {
                if (num % i == 0) {
                    sumDivisors += i;
                    countDivisors++;
                    if (num / i != i) {
                        sumDivisors += num / i;
                        countDivisors++;
                    }
                }
                if (countDivisors > 4) {
                    break;
                }
            }
            if (countDivisors == 4) {
                result += sumDivisors;
            }
        }
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1390 (Four Divisors)?

This page provides optimized solutions for LeetCode problem 1390 (Four Divisors) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1390 (Four Divisors)?

The time complexity for LeetCode 1390 (Four Divisors) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1390 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1390 in Java, C++, or Python.

Back to LeetCode Solutions