
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Four Divisors in C++
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 −
#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
- Related Articles
- Closest Divisors in C++
- Divisors of n-square that are not divisors of n in C++ Program
- Greatest common divisors in Python
- Find sum of divisors of all the divisors of a natural number in C++
- Count divisors of array multiplication in C++
- Find number from its divisors in C++
- Divisors of factorials of a number in java
- Minimum number of Square Free Divisors in C++
- Count all perfect divisors of a number in C++
- Find all divisors of a natural number in java
- Program to maximize number of nice divisors in Python
- Counting divisors of a number using JavaScript
- Find A and B from list of divisors in C++
- C++ Program for Common Divisors of Two Numbers?
- Python Program for Common Divisors of Two Numbers
