Open In App
Related Articles

Find sum of factorials in an array

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Given an array arr[] of N integers. The task is to find the sum of factorials of each element of the array.

Examples: 

Input: arr[] = {7, 3, 5, 4, 8} 
Output: 45510 
7! + 3! + 5! + 4! + 8! = 5040 + 6 + 120 + 24 + 40320 = 45510

Input: arr[] = {2, 1, 3} 
Output:
 

Approach: Implement a function factorial(n) that finds the factorial of n and initialize sum = 0. Now, traverse the given array and for each element arr[i] update sum = sum + factorial(arr[i]). Print the calculated sum in the end.

Below is the implementation of the above approach:  

C++

// C++ implementation of the approach
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the factorial of n
int factorial(int n)
{
    int f = 1;
    for (int i = 1; i <= n; i++)
    {
        f *= i;
    }
    return f;
}
 
// Function to return the sum of
// factorials of the array elements
int sumFactorial(int *arr, int n)
{
 
    // To store the required sum
    int s = 0,i;
    for (i = 0; i < n; i++)
    {
 
        // Add factorial of all the elements
        s += factorial(arr[i]);
    }
    return s;
}
 
// Driver code
int main()
{
    int arr[] = { 7, 3, 5, 4, 8 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << sumFactorial(arr, n);
    return 0;
}
     
// This code is contributed by 29AjayKumar

                    

Java

// Java implementation of the approach
class GFG {
 
    // Function to return the factorial of n
    static int factorial(int n)
    {
        int f = 1;
        for (int i = 1; i <= n; i++) {
            f *= i;
        }
        return f;
    }
 
    // Function to return the sum of
    // factorials of the array elements
    static int sumFactorial(int[] arr, int n)
    {
 
        // To store the required sum
        int s = 0;
        for (int i = 0; i < n; i++) {
 
            // Add factorial of all the elements
            s += factorial(arr[i]);
        }
        return s;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[] arr = { 7, 3, 5, 4, 8 };
        int n = arr.length;
        System.out.println(sumFactorial(arr, n));
    }
}

                    

Python3

# Python implementation of the approach
 
# Function to return the factorial of n
def factorial(n):
    f = 1;
    for i in range(1, n + 1):
        f *= i;
    return f;
 
# Function to return the sum of
# factorials of the array elements
def sumFactorial(arr, n):
 
    # To store the required sum
    s = 0;
    for i in range(0,n):
 
        # Add factorial of all the elements
        s += factorial(arr[i]);
    return s;
 
# Driver code
arr = [7, 3, 5, 4, 8 ];
n = len(arr);
print(sumFactorial(arr, n));
 
# This code contributed by Rajput-Ji

                    

C#

// C# implementation of the approach
using System;
 
class GFG
{
 
    // Function to return the factorial of n
    static int factorial(int n)
    {
        int f = 1;
        for (int i = 1; i <= n; i++)
        {
            f *= i;
        }
        return f;
    }
 
    // Function to return the sum of
    // factorials of the array elements
    static int sumFactorial(int[] arr, int n)
    {
 
        // To store the required sum
        int s = 0;
        for (int i = 0; i < n; i++)
        {
 
            // Add factorial of all the elements
            s += factorial(arr[i]);
        }
        return s;
    }
 
    // Driver Code
    public static void Main()
    {
        int[] arr = { 7, 3, 5, 4, 8 };
        int n = arr.Length;
        Console.WriteLine(sumFactorial(arr, n));
    }
}
 
// This code is contributed by Ryuga

                    

PHP

<?php
 
// PHP implementation of the approach
 
// Function to return the factorial of n
function factorial( $n)
{
    $f = 1;
    for ( $i = 1; $i <= $n; $i++)
    {
        $f *=$i;
    }
    return $f;
}
 
// Function to return the sum of
// factorials of the array elements
function sumFactorial($arr$n)
{
 
    // To store the required sum
    $s = 0;
    for ($i = 0; $i < $n; $i++)
    {
 
        // Add factorial of all the elements
        $s += factorial($arr[$i]);
    }
    return $s;
}
 
// Driver code
 
$arr = array( 7, 3, 5, 4, 8 );
$n = sizeof($arr);
echo sumFactorial($arr, $n);
 
// This code is contributed by ihritik
 
?>
    

                    

Javascript

// Javascript implementation of the approach
 
// Function to return the factorial of n
function factorial(n)
{
    let f = 1;
    for(let i = 1; i <= n; i++)
    {
        f *= i;
    }
    return f;
}
 
// Function to return the sum of
// factorials of the array elements
function sumFactorial(arr, n)
{
 
    // To store the required sum
    let s = 0;
    for (let i = 0; i < n; i++)
    {
         
        // Add factorial of all the elements
        s += factorial(arr[i]);
    }
    return s;
}
 
// Driver code
let arr = [ 7, 3, 5, 4, 8 ];
let n = arr.length;
 
console.log(sumFactorial(arr, n));
 
// This code is contributed by bobby

                    

Output: 
45510

 

Time Complexity: O(n2)

Auxiliary Space: O(1)

Efficient Approach( Using Hashmap): we will  store the all factorial of a number till maximum element of the array in hashmap. Then , we will iterate the whole array and update sum to sum + fac[i] which is precalculated . And finally return the total sum .

Below is the implementation of the above approach:  

C++

// C++ implementation of the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function find the sum of
// factorials of the all array elements
int sumFactorial(int *arr, int n)
{
    map<int,int> fac; // For storing factorial that
    fac[1] = 1;       // calculated already
    int m = *max_element(arr, arr+n);//maximum element of the array
   
    int sum = 0, i;
    for (i = 2; i <= m; i++) // finding factorial till maximum
    {    fac[i] = fac[i-1] * i; } // element of the array
     
    for (i = 0; i < n; i++)   // Adding sum of factorial of
    {    sum += fac[arr[i]]; }  // all array element
    
    return sum; // return final sum 
}
 
// Drive code
int main()
{
    int arr[] = { 7, 3, 5, 4, 8 };
    int n = sizeof(arr) / sizeof(arr[0]);
   
    // Function call
    cout << sumFactorial(arr, n);
    return 0;
}
 
// This Approach is contributed by nikhilsainiofficial546

                    

Python3

import math
 
# Function to find the sum of
# factorials of all array elements
def sumFactorial(arr, n):
 
    # For storing factorials that
    # have already been calculated
    fac = {1: 1}
 
    # Find maximum element of the array
    m = max(arr)
 
    sum = 0
    for i in range(2, m+1):
        fac[i] = fac[i-1] * i # finding factorial till maximum element of the array
     
    for i in range(n):
        sum += fac[arr[i]] # Adding sum of factorial of all array element
     
    return sum # Return final sum
 
# Driver code
arr = [7, 3, 5, 4, 8]
n = len(arr)
 
# Function call
print(sumFactorial(arr, n))

                    

Java

// Java implementation of the above approach
 
import java.util.*;
 
public class GFG {
    // Function find the sum of
    // factorials of the all array elements
    public static int sumFactorial(int[] arr, int n)
    {
        Map<Integer, Integer> fac
            = new HashMap<>(); // For storing factorial that
        fac.put(1, 1); // calculated already
        int m = Arrays.stream(arr)
                    .max()
                    .getAsInt(); // maximum element of the
                                 // array
        int sum = 0, i;
        for (i = 2; i <= m;
             i++) { // finding factorial till maximum
            fac.put(i, fac.get(i - 1) * i);
        }
 
        for (i = 0; i < n;
             i++) { // Adding sum of factorial of
            sum += fac.get(arr[i]); // all array element
        }
 
        return sum; // return final sum
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int[] arr = { 7, 3, 5, 4, 8 };
        int n = arr.length;
 
        // Function call
        System.out.println(sumFactorial(arr, n));
    }
}

                    

C#

// C# implementation of the above approach
 
using System;
using System.Collections.Generic;
using System.Linq;
 
class GFG {
 
    // Function find the sum of
    // factorials of the all array elements
    static int SumFactorial(int[] arr)
    {
        Dictionary<int, int> fac
            = new Dictionary<int, int>(); // For storing
                                          // factorial that
        fac[1] = 1; // calculated already
        int m = arr.Max(); // maximum element of the array
 
        int sum = 0, i;
        for (i = 2; i <= m;
             i++) // finding factorial till maximum
        {
            fac[i] = fac[i - 1] * i;
        } // element of the array
 
        foreach(int elem in arr) // Adding sum of factorial
                                 // of all array element
        {
            sum += fac[elem];
        }
 
        return sum; // return final sum
    }
 
    public static void Main(string[] args)
    {
        int[] arr = { 7, 3, 5, 4, 8 };
        Console.WriteLine(
            SumFactorial(arr)); // Function call
    }
}

                    

Javascript

function sumFactorial(arr, n) {
 
  // For storing factorials that have already been calculated
  let fac = {1: 1};
 
  // Find maximum element of the array
  let m = Math.max(...arr);
 
  let sum = 0;
  for (let i = 2; i <= m; i++) {
    fac[i] = fac[i-1] * i; // finding factorial till maximum element of the array
  }
   
  for (let i = 0; i < n; i++) {
    sum += fac[arr[i]]; // Adding sum of factorial of all array element
  }
   
  return sum; // Return final sum
}
 
// Driver code
let arr = [7, 3, 5, 4, 8];
let n = arr.length;
 
// Function call
console.log(sumFactorial(arr, n));

                    

Output
45510

Time Complexity: O(max(n,m)) , where m is the maximum element of the array and n is the no. of array element .

Auxiliary Space: O(m)



Last Updated : 24 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads