Similar Problems

Similar Problems not available

Four Divisors - Leetcode Solution

Companies:

LeetCode:  Four Divisors Leetcode Solution

Difficulty: Medium

Topics: math array  

The Four Divisors problem on LeetCode asks you to find the sum of all numbers which have exactly four divisors.

Here is a step-by-step solution to the problem:

  1. Create a function called "sumFourDivisors" that takes in an integer array called "nums" and returns an integer.
  2. Initialize a variable called "sum" to 0, which will be used to store the sum of the numbers that have exactly four divisors.
  3. Loop through each number in the "nums" array and do the following: a. Calculate the square root of the current number and round it up to the nearest integer. This will be used as the upper bound for the divisors. b. Initialize a variable called "divCount" to 0, which will be used to count the number of divisors for the current number. c. Loop through all numbers from 1 to the square root of the current number, inclusive. If the current number is divisible by the current divisor, increment the "divCount" variable by 2 (since both the divisor and its complement will be counted). d. If the current number is a perfect square, decrement the "divCount" by 1 to avoid counting the square root twice. e. If the "divCount" is exactly 4, add the current number to the "sum" variable.
  4. Return the "sum" variable.
  5. Test the function with sample input to ensure it's calculating sum of all numbers which have exactly four divisors correctly.

Here is the code for the solution:

function sumFourDivisors(nums) {
  let sum = 0;

  for (let i = 0; i < nums.length; i++) {
    let upperBound = Math.ceil(Math.sqrt(nums[i]));
    let divCount = 0;

    for (let j = 1; j <= upperBound; j++) {
      if (nums[i] % j === 0) {
        divCount += 2;
        if (nums[i] / j === j) {
          divCount--;
        }
      }
    }

    if (divCount === 4) {
      sum += nums[i];
    }
  }

  return sum;
}

Overall, this solution has a time complexity of O(n * sqrt(n)), which is the time complexity of looping through each number and its divisors. This should be efficient enough to handle large input sizes.

Four Divisors Solution Code

1