The Wayback Machine - https://web.archive.org/web/20240627105642/https://www.geeksforgeeks.org/sum-divisors-factorial-number/
Open In App

Sum of divisors of factorial of a number

Last Updated : 13 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a number n, we need to calculate the sum of divisors of factorial of the number.

Examples: 

Input : 4
Output : 60
Factorial of 4 is 24. Divisors of 24 are
1 2 3 4 6 8 12 24, sum of these is 60.

Input : 6
Output : 2418

A Simple Solution is to first compute the factorial of the given number, then count the number divisors of the factorial. This solution is not efficient and may cause overflow due to factorial computation.

Below is the implementation of the above approach:  

C++




// C++ program to find sum of proper divisor of
// factorial of a number
#include <bits/stdc++.h>
using namespace std;
 
// function to calculate factorial
int fact(int n)
{
    if (n == 0)
        return 1;
    return n * fact(n - 1);
}
 
// function to calculate sum of divisor
int div(int x)
{
    int ans = 0;
    for (int i = 1; i<= x; i++)
        if (x % i == 0)
            ans += i;
    return ans;
}
 
// Returns sum of divisors of n!
int sumFactDiv(int n)
{
    return div(fact(n));
}
 
// Driver Code
int main()
{
    int n = 4;
    cout << sumFactDiv(n);
}
 
// This code is contributed
// by Akanksha Rai


C




// C program to find sum of proper divisor of
// factorial of a number
#include <stdio.h>
// function to calculate factorial
 
int fact(int n) {
    if (n == 0)
        return 1;
    return n * fact(n - 1);
}
 
// function to calculate sum of divisor
 
int div(int x) {
    int ans = 0;
    for (int i = 1; i<= x; i++)
        if (x % i == 0)
            ans += i;
    return ans;
}
 
// Returns sum of divisors of n!
 
int sumFactDiv(int n) {
    return div(fact(n));
}
 
// driver program
 
int main() {
    int n = 4;
    printf("%d",sumFactDiv(n));
}


Java




// Java program to find sum of proper divisor of
// factorial of a number
import java.io.*;
import java.util.*;
 
public class Division
{
    // function to calculate factorial
    static int fact(int n)
    {
        if (n == 0)
            return 1;
        return n*fact(n-1);
    }
 
    // function to calculate sum of divisor
    static int div(int x)
    {
        int ans = 0;
        for (int i = 1; i<= x; i++)
            if (x%i == 0)
                ans += i;
        return ans;
    }
 
    // Returns sum of divisors of n!
    static int sumFactDiv(int n)
    {
        return div(fact(n));
    }
 
    // driver program
    public static void main(String args[])
    {
        int n = 4;
        System.out.println(sumFactDiv(n));
    }
}


Python3




# Python 3 program to find sum of proper
# divisor of factorial of a number
 
# function to calculate factorial
def fact(n):
     
    if (n == 0):
        return 1
    return n * fact(n - 1)
 
# function to calculate sum
# of divisor
def div(x):
    ans = 0;
    for i in range(1, x + 1):
        if (x % i == 0):
            ans += i
    return ans
 
# Returns sum of divisors of n!
def sumFactDiv(n):
    return div(fact(n))
 
# Driver Code
n = 4
print(sumFactDiv(n))
 
# This code is contributed
# by Rajput-Ji


C#




// C# program to find sum of proper
// divisor of factorial of a number
using System;
class Division {
     
    // function to calculate factorial
    static int fac(int n)
    {
        if (n == 0)
            return 1;
        return n * fac(n - 1);
    }
 
    // function to calculate
    // sum of divisor
    static int div(int x)
    {
        int ans = 0;
        for (int i = 1; i <= x; i++)
            if (x % i == 0)
                ans += i;
        return ans;
    }
 
    // Returns sum of divisors of n!
    static int sumFactDiv(int n)
    {
        return div(fac(n));
    }
 
    // Driver Code
    public static void Main()
    {
        int n = 4;
        Console.Write(sumFactDiv(n));
    }
}
 
// This code is contributed by Nitin Mittal.


PHP




<?php
// PHP program to find sum of proper
// divisor of factorial of a number
 
// function to calculate factorial
function fact($n)
{
    if ($n == 0)
        return 1;
    return $n * fact($n - 1);
}
 
// function to calculate sum of divisor
function div($x)
{
    $ans = 0;
    for ($i = 1; $i<= $x; $i++)
        if ($x % $i == 0)
            $ans += $i;
    return $ans;
}
 
// Returns sum of divisors of n!
function sumFactDiv($n)
{
    return div(fact($n));
}
 
// Driver Code
$n = 4;
echo sumFactDiv($n);
 
// This code is contributed
// by Akanksha Rai
?>


Javascript




<script>
// JavaScript program to find
// sum of proper divisor of
// factorial of a number
 
// function to calculate factorial
function fact(n)
{
    if (n == 0)
        return 1;
    return n * fact(n - 1);
}
 
// function to calculate sum of divisor
function div(x)
{
    let ans = 0;
    for (let i = 1; i<= x; i++)
        if (x % i == 0)
            ans += i;
    return ans;
}
 
// Returns sum of divisors of n!
function sumFactDiv(n)
{
    return div(fact(n));
}
 
// Driver Code
 
    let n = 4;
    document.write(sumFactDiv(n));
 
 
// This code is contributed by Surbhi Tyagi.
 
</script>


Output : 

60

Time Complexity: O(n!)

Auxiliary Space: O(1)

An efficient solution is based on Legendre’s formula. Below are the steps. 

  1. Find all prime numbers less than or equal to n (input number). We can use Sieve Algorithm for this. Let n be 6. All prime numbers less than 6 are {2, 3, 5}.
  2. For each prime number, p find the largest power of it that divides n!. We use Legendre’s formula for this purpose.
    • The largest power of 2 that divides 6!, exp1 = 4.
    • The largest power of 3 that divides 6!, exp2 = 2.
    • The largest power of 5 that divides 6!, exp3 = 1.
  3. The result is based on the Divisor Function. 

C++




// C++ program to find sum of divisors in n!
#include<bits/stdc++.h>
#include<math.h>
using namespace std;
 
// allPrimes[] stores all prime numbers less
// than or equal to n.
vector<int> allPrimes;
 
// Fills above vector allPrimes[] for a given n
void sieve(int n)
{
    // Create a boolean array "prime[0..n]" and
    // initialize all entries it as true. A value
    // in prime[i] will finally be false if i is
    // not a prime, else true.
    vector<bool> prime(n+1, true);
 
    // Loop to update prime[]
    for (int p = 2; p*p <= n; p++)
    {
        // If prime[p] is not changed, then it
        // is a prime
        if (prime[p] == true)
        {
            // Update all multiples of p
            for (int i = p*2; i <= n; i += p)
                prime[i] = false;
        }
    }
 
    // Store primes in the vector allPrimes
    for (int p = 2; p <= n; p++)
        if (prime[p])
            allPrimes.push_back(p);
}
 
// Function to find all result of factorial number
int factorialDivisors(int n)
{
    sieve(n);  // create sieve
 
    // Initialize result
    int result = 1;
 
    // find exponents of all primes which divides n
    // and less than n
    for (int i = 0; i < allPrimes.size(); i++)
    {
        // Current divisor
        int p = allPrimes[i];
 
        // Find the highest power (stored in exp)'
        // of allPrimes[i] that divides n using
        // Legendre's formula.
        int exp = 0;
        while (p <= n)
        {
            exp = exp + (n/p);
            p = p*allPrimes[i];
        }
 
        // Using the divisor function to calculate
        // the sum
        result = result*(pow(allPrimes[i], exp+1)-1)/
                                    (allPrimes[i]-1);
    }
 
    // return total divisors
    return result;
}
 
// Driver program to run the cases
int main()
{
    cout << factorialDivisors(4);
    return 0;
}


Java




// Java program to find sum of divisors in n!
import java.util.*;
 
class GFG{
// allPrimes[] stores all prime numbers less
// than or equal to n.
static ArrayList<Integer> allPrimes=new ArrayList<Integer>();
 
// Fills above vector allPrimes[] for a given n
static void sieve(int n)
{
    // Create a boolean array "prime[0..n]" and
    // initialize all entries it as true. A value
    // in prime[i] will finally be false if i is
    // not a prime, else true.
    boolean[] prime=new boolean[n+1];
 
    // Loop to update prime[]
    for (int p = 2; p*p <= n; p++)
    {
        // If prime[p] is not changed, then it
        // is a prime
        if (prime[p] == false)
        {
            // Update all multiples of p
            for (int i = p*2; i <= n; i += p)
                prime[i] = true;
        }
    }
 
    // Store primes in the vector allPrimes
    for (int p = 2; p <= n; p++)
        if (prime[p]==false)
            allPrimes.add(p);
}
 
// Function to find all result of factorial number
static int factorialDivisors(int n)
{
    sieve(n); // create sieve
 
    // Initialize result
    int result = 1;
 
    // find exponents of all primes which divides n
    // and less than n
    for (int i = 0; i < allPrimes.size(); i++)
    {
        // Current divisor
        int p = allPrimes.get(i);
 
        // Find the highest power (stored in exp)'
        // of allPrimes[i] that divides n using
        // Legendre's formula.
        int exp = 0;
        while (p <= n)
        {
            exp = exp + (n/p);
            p = p*allPrimes.get(i);
        }
 
        // Using the divisor function to calculate
        // the sum
        result = result*((int)Math.pow(allPrimes.get(i), exp+1)-1)/
                                    (allPrimes.get(i)-1);
    }
 
    // return total divisors
    return result;
}
 
// Driver program to run the cases
public static void main(String[] args)
{
    System.out.println(factorialDivisors(4));
}
}
// This code is contributed by mits


Python3




# Python3 program to find sum of divisors in n!
 
# allPrimes[] stores all prime numbers
# less than or equal to n.
allPrimes = [];
 
# Fills above vector allPrimes[]
# for a given n
def sieve(n):
 
    # Create a boolean array "prime[0..n]"
    # and initialize all entries it as true.
    # A value in prime[i] will finally be
    # false if i is not a prime, else true.
    prime = [True] * (n + 1);
 
    # Loop to update prime[]
    p = 2;
    while (p * p <= n):
         
        # If prime[p] is not changed,
        # then it is a prime
        if (prime[p] == True):
             
            # Update all multiples of p
            for i in range(p * 2, n + 1, p):
                prime[i] = False;
        p += 1;
 
    # Store primes in the vector allPrimes
    for p in range(2, n + 1):
        if (prime[p]):
            allPrimes.append(p);
 
# Function to find all result of factorial number
def factorialDivisors(n):
 
    sieve(n); # create sieve
 
    # Initialize result
    result = 1;
 
    # find exponents of all primes which
    # divides n and less than n
    for i in range(len(allPrimes)):
         
        # Current divisor
        p = allPrimes[i];
 
        # Find the highest power (stored in exp)'
        # of allPrimes[i] that divides n using
        # Legendre's formula.
        exp = 0;
        while (p <= n):
            exp = exp + int(n / p);
            p = p * allPrimes[i];
 
        # Using the divisor function to 
        # calculate the sum
        result = int(result * (pow(allPrimes[i], exp + 1) - 1) /
                                           (allPrimes[i] - 1));
 
    # return total divisors
    return result;
 
# Driver Code
print(factorialDivisors(4));
 
# This code is contributed by mits


C#




// C# program to find sum of divisors in n!
using System;
using System.Collections;
 
class GFG{
// allPrimes[] stores all prime numbers less
// than or equal to n.
static ArrayList allPrimes=new ArrayList();
 
// Fills above vector allPrimes[] for a given n
static void sieve(int n)
{
    // Create a boolean array "prime[0..n]" and
    // initialize all entries it as true. A value
    // in prime[i] will finally be false if i is
    // not a prime, else true.
    bool[] prime=new bool[n+1];
 
    // Loop to update prime[]
    for (int p = 2; p*p <= n; p++)
    {
        // If prime[p] is not changed, then it
        // is a prime
        if (prime[p] == false)
        {
            // Update all multiples of p
            for (int i = p*2; i <= n; i += p)
                prime[i] = true;
        }
    }
 
    // Store primes in the vector allPrimes
    for (int p = 2; p <= n; p++)
        if (prime[p]==false)
            allPrimes.Add(p);
}
 
// Function to find all result of factorial number
static int factorialDivisors(int n)
{
    sieve(n); // create sieve
 
    // Initialize result
    int result = 1;
 
    // find exponents of all primes which divides n
    // and less than n
    for (int i = 0; i < allPrimes.Count; i++)
    {
        // Current divisor
        int p = (int)allPrimes[i];
 
        // Find the highest power (stored in exp)'
        // of allPrimes[i] that divides n using
        // Legendre's formula.
        int exp = 0;
        while (p <= n)
        {
            exp = exp + (n/p);
            p = p*(int)allPrimes[i];
        }
 
        // Using the divisor function to calculate
        // the sum
        result = result*((int)Math.Pow((int)allPrimes[i], exp+1)-1)/
                                    ((int)allPrimes[i]-1);
    }
 
    // return total divisors
    return result;
}
 
// Driver program to run the cases
static void Main()
{
    Console.WriteLine(factorialDivisors(4));
}
}
// This code is contributed by mits


PHP




<?php
// PHP program to find sum of divisors in n!
 
// allPrimes[] stores all prime numbers less
// than or equal to n.
$allPrimes=array();
 
// Fills above vector allPrimes[] for a given n
function sieve($n)
{
    global $allPrimes;
    // Create a boolean array "prime[0..n]" and
    // initialize all entries it as true. A value
    // in prime[i] will finally be false if i is
    // not a prime, else true.
    $prime=array_fill(0,$n+1,true);
 
    // Loop to update prime[]
    for ($p = 2; $p*$p <= $n; $p++)
    {
        // If prime[p] is not changed, then it
        // is a prime
        if ($prime[$p] == true)
        {
            // Update all multiples of p
            for ($i = $p*2; $i <= $n; $i += $p)
                $prime[$i] = false;
        }
    }
 
    // Store primes in the vector allPrimes
    for ($p = 2; $p <= $n; $p++)
        if ($prime[$p])
            array_push($allPrimes,$p);
}
 
// Function to find all result of factorial number
function factorialDivisors($n)
{
    global $allPrimes;
    sieve($n); // create sieve
 
    // Initialize result
    $result = 1;
 
    // find exponents of all primes which divides n
    // and less than n
    for ($i = 0; $i < count($allPrimes); $i++)
    {
        // Current divisor
        $p = $allPrimes[$i];
 
        // Find the highest power (stored in exp)'
        // of allPrimes[i] that divides n using
        // Legendre's formula.
        $exp = 0;
        while ($p <= $n)
        {
            $exp = $exp + (int)($n/$p);
            $p = $p*$allPrimes[$i];
        }
 
        // Using the divisor function to calculate
        // the sum
        $result = $result*(pow($allPrimes[$i], $exp+1)-1)/
                                    ($allPrimes[$i]-1);
    }
 
    // return total divisors
    return $result;
}
 
// Driver program to run the cases
 
    print(factorialDivisors(4));
 
 
// This code is contributed by mits
?>


Javascript




<script>
 
// Javascript program to find sum of divisors in n!
 
// allPrimes[] stores all prime numbers less
// than or equal to n.
let allPrimes=[];
 
// Fills above vector allPrimes[] for a given n
function sieve(n)
{
     
    // Create a boolean array "prime[0..n]" and
    // initialize all entries it as true. A value
    // in prime[i] will finally be false if i is
    // not a prime, else true.
    let prime = new Array(n + 1);
    for(let i = 0; i < n + 1; i++)
        prime[i] = true;
  
    // Loop to update prime[]
    for(let p = 2; p * p <= n; p++)
    {
         
        // If prime[p] is not changed, then it
        // is a prime
        if (prime[p] == true)
        {
             
            // Update all multiples of p
            for(let i = p * 2; i <= n; i += p)
                prime[i] = false;
        }
    }
  
    // Store primes in the vector allPrimes
    for(let p = 2; p <= n; p++)
        if (prime[p])
            allPrimes.push(p);
}
 
// Function to find all result of
// factorial number
function factorialDivisors(    n)
{
     
    // Create sieve
    sieve(n);
  
    // Initialize result
    let result = 1;
  
    // Find exponents of all primes which
    // divides n and less than n
    for(let i = 0; i < allPrimes.length; i++)
    {
         
        // Current divisor
        let p = allPrimes[i];
  
        // Find the highest power (stored in exp)'
        // of allPrimes[i] that divides n using
        // Legendre's formula.
        let exp = 0;
         
        while (p <= n)
        {
            exp = exp + Math.floor(n/p);
            p = p*allPrimes[i];
        }
  
        // Using the divisor function to calculate
        // the sum
        result = Math.floor(result * (Math.pow(
                 allPrimes[i], exp + 1) - 1) /
                     (allPrimes[i] - 1));
    }
  
    // Return total divisors
    return result;
}
 
// Driver code
document.write(factorialDivisors(4));
 
// This code is contributed by rag2127
 
</script>


Output: 

60

Time Complexity: O(n*log(log(n)))

Auxiliary Space: O(n)

 



Previous Article
Next Article

Similar Reads

Find sum of inverse of the divisors when sum of divisors and the number is given
Given an integer N and the sum of its divisors. The task is to find the sum of the inverse of the divisors of N.Examples: Input: N = 6, Sum = 12 Output: 2.00 Divisors of N are {1, 2, 3, 6} Sum of inverse of divisors is equal to (1/1 + 1/2 + 1/3 + 1/6) = 2.0Input: N = 9, Sum = 13 Output: 1.44 Naive Approach: Calculate all the divisors of the given i
3 min read
Find sum of divisors of all the divisors of a natural number
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. I
7 min read
Find the last digit when factorial of A divides factorial of B
We are given two numbers A and B such that B &gt;= A. We need to compute the last digit of this resulting F such that F = B!/A! where 1 = A, B &lt;= 10^18 (A and B are very large).Examples: Input : A = 2, B = 4Output : 2Explanation : A! = 2 and B! = 24. F = 24/2 = 12 --&gt; last digit = 2Input : 107 109Output : 2 Recommended PracticeFind the last d
10 min read
Check if a number has an odd count of odd divisors and even count of even divisors
Given an integer N, the task is to check if N has an odd number of odd divisors and even number of even divisors. Examples: Input: N = 36Output: YesExplanation:Divisors of 36 = 1, 2, 3, 4, 6, 9, 12, 18, 36Count of Odd Divisors(1, 3, 9) = 3 [Odd]Count of Even Divisors(2, 4, 6, 12, 18, 36) = 6 [Even] Input: N = 28Output: No Naive Approach: The idea i
9 min read
Count Divisors of Factorial
Given a number n, count the total number of divisors of n!. Examples: Input : n = 4Output: 8Explanation:4! is 24. Divisors of 24 are 1, 2, 3, 4, 6,8, 12 and 24. Input : n = 5Output : 16Explanation:5! is 120. Divisors of 120 are 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24 30, 40, 60 and 12 Recommended PracticeCount Divisors of FactorialTry It! A Simple
11 min read
Divisors of n-square that are not divisors of n
Given an positive large integer n. Count the number of positive divisors of n2 which are not divisible by any divisor of n(1 &lt;= n &lt;= 1012). Input: 6 Output: 5 Explanation Total divisors of 62 are 9 i.e., 1, 2, 3, 4, 6, 9, 12, 18, 36 Total divisors of '6' are 4, 1, 2, 3, 6 Total divisor of '36' which are not divisible by divisors of '6' are '5
7 min read
Check if count of even divisors of N is equal to count of odd divisors
Given a positive integer N, the task is to check whether the count of even divisors and odd divisors of N are equal or not. If they are same then print "YES" else print "NO".Examples : Input: N = 6 Output: YES Explanation: Number 6 has four factors: 1, 2, 3, 6, count of even divisors = 2 (2 and 6) count of odd divisors = 2 (1 and 3)Input: N = 9 Out
9 min read
Minimum value exceeding X whose count of divisors has different parity with count of divisors of X
Given an integer X, the task is to determine the minimum value of Y greater than X, such that count of divisors of X and Y have different parities. Examples: Input: X = 5Output: 9Explanation: The count of divisors of 5 and 9 are 2 and 3 respectively, which are of different parities. Input: X = 9Output: 10Explanation: The counts of divisors of 9 and
8 min read
Maximum possible prime divisors that can exist in numbers having exactly N divisors
Given an integer N which denotes the number of divisors of any number, the task is to find the maximum prime divisors that are possible in number having N divisors. Examples: Input: N = 4 Output: 2 Input: N = 8 Output: 3 Naive Approach: In this approach, the idea is to generate all the numbers having exactly N divisors and check for the maximum num
11 min read
Check if a subarray of length K with sum equal to factorial of a number exists or not
Given an array arr[] of N integers and an integer K, the task is to find a subarray of length K with a sum of elements equal to factorial of any number. If no such subarray exists, print “-1”. Examples: Input: arr[] = {23, 45, 2, 4, 6, 9, 3, 32}, K = 5Output: 2 4 6 9 3Explanation:Subarray {2, 4, 6, 9, 3} with sum 24 (= 4!) satisfies the required co
12 min read
three90RightbarBannerImg