Four Divisors in C++

C++Server Side ProgrammingProgramming

Suppose we have an integer array nums, we have to find the sum of divisors of the integers in that array that have exactly four divisors. So if there is no such integer in the array, then return 0. For example, if the input is [21, 4, 7], then the output will be 32, as 21 has four divisors 1, 3, 7, 21, 4 has three divisors 1, 2, 4, and 7 has two divisors 1 and 7. The answer is the sum of the divisors of the 21 only.

To solve this, we will follow these steps −

  • Define a method called ok(), this will take x as input

  • ret := 1 + x, cnt := 2

  • for i := 2, i^2 <= x, increase i by 1

    • if x is divisible by i

      • increase ret by i, increase cnt by 1

      • if i is not x/i, then increase cnt by 1, ret := ret + (x/i)

  • return ret, if cnt is 4, otherwise return 0

  • From the main method

  • ret := 0, n := size of nums

  • for i in range 0 to n – 1

    • ret := ret + ok(nums[i])

  • return ret

Example (C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int ok(int x){
      int ret = 1 + x;;
      int cnt = 2;
      for(int i = 2; i * i <= x; i++){
         if(x % i == 0){
            ret += (i);
            cnt++;
            if(i != x / i){
               cnt++;
               ret += (x / i);
            }
         }
      }
      return cnt == 4 ? ret : 0;
   }
   int sumFourDivisors(vector<int>& nums) {
      int ret = 0;
      int n = nums.size();
      for(int i = 0; i < n; i++){
         ret += ok(nums[i]);
      }
      return ret;
   }
};
main(){
   vector<int> v = {21,4,7};
   Solution ob;
   cout << (ob.sumFourDivisors(v));
}

Input

[21,4,7]

Output

32
raja
Published on 31-Mar-2020 08:26:40
Advertisements