Find sum of divisors of all the divisors of a natural number
Last Updated :
23 Jun, 2022
Given a natural number n, the task is to find sum of divisors of all the divisors of n.
Examples:
Input : n = 54
Output : 232
Divisors of 54 = 1, 2, 3, 6, 9, 18, 27, 54.
Sum of divisors of 1, 2, 3, 6, 9, 18, 27, 54
are 1, 3, 4, 12, 13, 39, 40, 120 respectively.
Sum of divisors of all the divisors of 54 =
1 + 3 + 4 + 12 + 13 + 39 + 40 + 120 = 232.
Input : n = 10
Output : 28
Divisors of 10 are 1, 2, 5, 10
Sums of divisors of divisors are
1, 3, 6, 18.
Overall sum = 1 + 3 + 6 + 18 = 28
Using the fact that any number n can be expressed as product of prime factors, n = p1k1 x p2k2 x ... where p1, p2, ... are prime numbers.
All the divisors of n can be expressed as p1a x p2b x ..., where 0 <= a <= k1 and 0 <= b <= k2.
Now sum of divisors will be sum of all power of p1 - p10, p11,...., p1k1 multiplied by all power of p2 - p20, p21,...., p2k1
Sum of Divisor of n
= (p10 x p20) + (p11 x p20) +.....+ (p1k1 x p20) +....+ (p10 x p21) + (p11 x p21) +.....+ (p1k1 x p21) +........+
(p10 x p2k2) + (p11 x p2k2) +......+ (p1k1 x p2k2).
= (p10 + p11 +...+ p1k1) x p20 + (p10 + p11 +...+ p1k1) x p21 +.......+ (p10 + p11 +...+ p1k1) x p2k2.
= (p10 + p11 +...+ p1k1) x (p20 + p21 +...+ p2k2).
Now, the divisors of any pa, for p as prime, are p0, p1,......, pa. And sum of divisors will be (p(a+1) - 1)/(p -1), let it define by f(p).
So, sum of divisors of all divisor will be,
= (f(p10) + f(p11) +...+ f(p1k1)) x (f(p20) + f(p21) +...+ f(p2k2)).
So, given a number n, by prime factorization we can find the sum of divisors of all the divisors. But in this problem we are given that n is product of element of array. So, find prime factorization of each element and by using the fact ab x ac = ab+c.
Below is the implementation of this approach:
C++
// C++ program to find sum of divisors of all
// the divisors of a natural number.
#include<bits/stdc++.h>
using namespace std;
// Returns sum of divisors of all the divisors
// of n
int sumDivisorsOfDivisors(int n)
{
// Calculating powers of prime factors and
// storing them in a map mp[].
map<int, int> mp;
for (int j=2; j<=sqrt(n); j++)
{
int count = 0;
while (n%j == 0)
{
n /= j;
count++;
}
if (count)
mp[j] = count;
}
// If n is a prime number
if (n != 1)
mp[n] = 1;
// For each prime factor, calculating (p^(a+1)-1)/(p-1)
// and adding it to answer.
int ans = 1;
for (auto it : mp)
{
int pw = 1;
int sum = 0;
for (int i=it.second+1; i>=1; i--)
{
sum += (i*pw);
pw *= it.first;
}
ans *= sum;
}
return ans;
}
// Driven Program
int main()
{
int n = 10;
cout << sumDivisorsOfDivisors(n);
return 0;
}
Java
// Java program to find sum of divisors of all
// the divisors of a natural number.
import java.util.HashMap;
class GFG
{
// Returns sum of divisors of all the divisors
// of n
public static int sumDivisorsOfDivisors(int n)
{
// Calculating powers of prime factors and
// storing them in a map mp[].
HashMap<Integer, Integer> mp = new HashMap<>();
for (int j = 2; j <= Math.sqrt(n); j++)
{
int count = 0;
while (n % j == 0)
{
n /= j;
count++;
}
if (count != 0)
mp.put(j, count);
}
// If n is a prime number
if (n != 1)
mp.put(n, 1);
// For each prime factor, calculating (p^(a+1)-1)/(p-1)
// and adding it to answer.
int ans = 1;
for (HashMap.Entry<Integer, Integer> entry : mp.entrySet())
{
int pw = 1;
int sum = 0;
for (int i = entry.getValue() + 1; i >= 1; i--)
{
sum += (i * pw);
pw *= entry.getKey();
}
ans *= sum;
}
return ans;
}
// Driver code
public static void main(String[] args)
{
int n = 10;
System.out.println(sumDivisorsOfDivisors(n));
}
}
// This code is contributed by
// sanjeev2552
Python3
# Python3 program to find sum of divisors
# of all the divisors of a natural number.
import math as mt
# Returns sum of divisors of all
# the divisors of n
def sumDivisorsOfDivisors(n):
# Calculating powers of prime factors
# and storing them in a map mp[].
mp = dict()
for j in range(2, mt.ceil(mt.sqrt(n))):
count = 0
while (n % j == 0):
n //= j
count += 1
if (count):
mp[j] = count
# If n is a prime number
if (n != 1):
mp[n] = 1
# For each prime factor, calculating
# (p^(a+1)-1)/(p-1) and adding it to answer.
ans = 1
for it in mp:
pw = 1
summ = 0
for i in range(mp[it] + 1, 0, -1):
summ += (i * pw)
pw *= it
ans *= summ
return ans
# Driver Code
n = 10
print(sumDivisorsOfDivisors(n))
# This code is contributed
# by mohit kumar 29
C#
// C# program to find sum of divisors of all
// the divisors of a natural number.
using System;
using System.Collections.Generic;
class GFG
{
// Returns sum of divisors of
// all the divisors of n
public static int sumDivisorsOfDivisors(int n)
{
// Calculating powers of prime factors and
// storing them in a map mp[].
Dictionary<int,
int> mp = new Dictionary<int,
int>();
for (int j = 2; j <= Math.Sqrt(n); j++)
{
int count = 0;
while (n % j == 0)
{
n /= j;
count++;
}
if (count != 0)
mp.Add(j, count);
}
// If n is a prime number
if (n != 1)
mp.Add(n, 1);
// For each prime factor,
// calculating (p^(a+1)-1)/(p-1)
// and adding it to answer.
int ans = 1;
foreach(KeyValuePair<int, int> entry in mp)
{
int pw = 1;
int sum = 0;
for (int i = entry.Value + 1;
i >= 1; i--)
{
sum += (i * pw);
pw = entry.Key;
}
ans *= sum;
}
return ans;
}
// Driver code
public static void Main(String[] args)
{
int n = 10;
Console.WriteLine(sumDivisorsOfDivisors(n));
}
}
// This code is contributed
// by Princi Singh
JavaScript
<script>
// Javascript program to find sum of divisors of all
// the divisors of a natural number.
// Returns sum of divisors of all the divisors
// of n
function sumDivisorsOfDivisors(n)
{
// Calculating powers of prime factors and
// storing them in a map mp[].
let mp = new Map();
for (let j = 2; j <= Math.sqrt(n); j++)
{
let count = 0;
while (n % j == 0)
{
n = Math.floor(n/j);
count++;
}
if (count != 0)
mp.set(j, count);
}
// If n is a prime number
if (n != 1)
mp.set(n, 1);
// For each prime factor, calculating (p^(a+1)-1)/(p-1)
// and adding it to answer.
let ans = 1;
for (let [key, value] of mp.entries())
{
let pw = 1;
let sum = 0;
for (let i = value + 1; i >= 1; i--)
{
sum += (i * pw);
pw = key;
}
ans *= sum;
}
return ans;
}
// Driver code
let n = 10;
document.write(sumDivisorsOfDivisors(n));
// This code is contributed by patel2127
</script>
Output:
28
Time Complexity: O(?n log n)
Auxiliary Space: O(n)
Optimizations :
For the cases when there are multiple inputs for which we need find the value, we can use Sieve of Eratosthenes as discussed in this post.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem