Find sum of divisors of all the divisors of a natural number in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a natural number N. Our task is to find the sum of divisors of all the divisors of a natural number.

Let's take an example to understand the problem,

Input : N = 12
Output : 55

Explanation

The divisors of 12 are 1, 2, 3, 4, 6, 12
Sum of divisors = (1) + (1 + 2) + (1 + 3) + (1 + 2 + 4) + (1 + 2 + 3 + 6) + (1 + 2 + 3 + 4 + 6 + 12) = 1 + 3 + 4 + 7 + 12 + 28 = 55

Solution Approach

A simple solution to the problem is using factorisation of N. Using prime factorisation, we can find the sum of divisors of all divisors. Here, we will find the prime factorisation of each element.

Example

Program to illustrate the working of our solution

#include<bits/stdc++.h>
using namespace std;
int findSumOfDivisorsOfDivisors(int n) {
   map<int, int> factorCount;
   for (int j=2; j<=sqrt(n); j++) {
      int count = 0;
      while (n%j == 0) {
         n /= j;
         count++;
      }
      if (count) 
         factorCount[j] = count;
   }
   if (n != 1)
      factorCount[n] = 1;
   int sumOfDiv = 1;
   for (auto it : factorCount) {
      int power = 1; 
      int sum = 0;
      for (int i=it.second+1; i>=1; i--) {
         sum += (i*power);
         power *= it.first;
      }
      sumOfDiv *= sum;
   }
   return sumOfDiv;
}
int main() {
   int n = 12;
   cout<<"The sum of divisors of all divisors is "<<findSumOfDivisorsOfDivisors(n);
   return 0;
}

Output

The sum of divisors of all divisors is 55
raja
Updated on 27-Jan-2022 08:11:18

Advertisements