
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Four Divisors in C++
In this article, we will understand the four divisors problem. We have an array of integers, and our task is to find the sum of divisors of the array elements that have exactly four divisors. If there is no such integer in the array, then return 0. Here is a detailed example given below:
Example
The following example implements four divisors sum problem:
Input: arr = [5, 10, 15, 8] Output: 57
The explanation of the above example is as follows:
Divisors of 5 = (1, 5) => count != 4 Divisors of 10 = 1, 2, 5, 10 => count = 4 => sum = 1+2+5+10 = 18 Divisors of 15 = (1, 3, 5, 15) => count = 4 => sum = 1+3+5+15 = 24 Divisors of 8 = (1, 2, 4, 8) => count = 4 => sum = 1+2+4+8 = 15 Total Sum = 18 + 24 + 15 = 57
Steps to Implement Four Divisors Problem
The steps to implement the four divisors problem are given below:
- We have initialized the count variable with 2 as the number itself and 1 is always divisors of the given number.
- The sumDiv() function calculates the sum of divisors of the array element having exactly 4 divisors.
- In the sumDiv() function, we iterate from the second index to the root of i to find the divisors of the number.
- If the given number num is divisible by the i(divisor), then we increase the counter and add this index in divSum.
- We also check not to include the same divisor twice. For example, 4 can be written as 2*2. So, we count 2 one time.
- At the end, we return the summation of divisors of each element having a count value of 4.
- The sumFour() function uses the sumDiv() function to sum the divisors of the array elements with exactly four divisors.
Implementing Four Divisors in C++
Here is the implementation of the above steps for finding the sum of divisors of array elements having exactly 4 divisors:
#include <bits/stdc++.h> using namespace std; // Calculating sum of divisors // if there is exactly 4 divisors int sumDiv(int num) { int divSum = 1 + num; // 1 and num are always divisors int count = 2; for (int i = 2; i * i <= num; i++) { if (num % i == 0) { divSum += i; count++; if (i != num / i) { divSum += (num / i); count++; } } } // Return sum only if exactly 4 divisors if (count == 4) return divSum; else return 0; } // Function for calculating sum for all numbers // having exactly 4 divisors int sumFour(vector<int> &nums) { int sum = 0; for (int i = 0; i < nums.size(); i++) { sum += sumDiv(nums[i]); } return sum; } int main() { vector<int> input = {21, 4, 7}; cout << "Given array is: "; for (int x : input) { cout << x << " "; } cout << "\nSum is: " << sumFour(input); }
The output of the above code is as follows:
Given array is: 21 4 7 Sum is: 32