Given a number n, write code to find the sum of digits in the factorial of the number. Given n ≤ 5000
Examples:
Input : 10
Output : 27
Input : 100
Output : 648
It is not possible to store a number as large as 100! under some data types so, idea is to store an extremely large number in a vector.
1) Create a vector to store factorial digits and
initialize it with 1.
2) One by one multiply numbers from 1 to n to
the vector. We use school mathematics for this
purpose.
3) Sum all the elements in vector and return the sum.
C++
#include <bits/stdc++.h>
using namespace std;
void multiply(vector<int> &v;, int x)
{
int carry = 0, res;
int size = v.size();
for (int i = 0 ; i < size ; i++)
{
int res = carry + v[i] * x;
v[i] = res % 10;
carry = res / 10;
}
while (carry != 0)
{
v.push_back(carry % 10);
carry /= 10;
}
}
int findSumOfDigits(int n)
{
vector<int> v;
v.push_back(1);
for (int i=1; i<=n; i++)
multiply(v, i);
int sum = 0;
int size = v.size();
for (int i = 0 ; i < size ; i++)
sum += v[i];
return sum;
}
int main()
{
int n = 1000;
cout << findSumOfDigits(n);
return 0;
}
|
Java
import java.util.*;
class GFG{
static ArrayList<Integer> v=new ArrayList<Integer>();
static void multiply(int x)
{
int carry = 0;
int size = v.size();
for (int i = 0 ; i < size ; i++)
{
int res = carry + v.get(i) * x;
v.set(i,res % 10);
carry = res / 10;
}
while (carry != 0)
{
v.add(carry % 10);
carry /= 10;
}
}
static int findSumOfDigits(int n)
{
v.add(1);
for (int i=1; i<=n; i++)
multiply(i);
int sum = 0;
int size = v.size();
for (int i = 0 ; i < size ; i++)
sum += v.get(i);
return sum;
}
public static void main(String[] args)
{
int n = 1000;
System.out.println(findSumOfDigits(n));
}
}
|
Python 3
def multiply(v, x):
carry = 0
size = len(v)
for i in range(size):
res = carry + v[i] * x
v[i] = res % 10
carry = res // 10
while (carry != 0):
v.append(carry % 10)
carry //= 10
def findSumOfDigits( n):
v = []
v.append(1)
for i in range(1, n + 1):
multiply(v, i)
sum = 0
size = len(v)
for i in range(size):
sum += v[i]
return sum
if __name__ == "__main__":
n = 1000
print(findSumOfDigits(n))
|
C#
using System;
using System.Collections;
class GFG{
static ArrayList v=new ArrayList();
static void multiply(int x)
{
int carry = 0;
int size = v.Count;
for (int i = 0 ; i < size ; i++)
{
int res = carry + (int)v[i] * x;
v[i] = res % 10;
carry = res / 10;
}
while (carry != 0)
{
v.Add(carry % 10);
carry /= 10;
}
}
static int findSumOfDigits(int n)
{
v.Add(1);
for (int i=1; i<=n; i++)
multiply(i);
int sum = 0;
int size = v.Count;
for (int i = 0 ; i < size ; i++)
sum += (int)v[i];
return sum;
}
static void Main()
{
int n = 1000;
Console.WriteLine(findSumOfDigits(n));
}
}
|
Javascript
<script>
let v=[];
function multiply(x)
{
let carry = 0;
let size = v.length;
for (let i = 0 ; i < size ; i++)
{
let res = carry + v[i] * x;
v[i]=res % 10;
carry = Math.floor(res / 10);
}
while (carry != 0)
{
v.push(carry % 10);
carry = Math.floor(carry/10);
}
}
function findSumOfDigits(n)
{
v.push(1);
for (let i=1; i<=n; i++)
multiply(i);
let sum = 0;
let size = v.length;
for (let i = 0 ; i < size ; i++)
sum += v[i];
return sum;
}
let n = 1000;
document.write(findSumOfDigits(n));
</script>
|
PHP
<?php
function multiply(&$v, $x)
{
$carry = 0;
$size = count($v);
for ($i = 0 ; $i < $size ; $i++)
{
$res = $carry + $v[$i] * $x;
$v[$i] = $res % 10;
$carry = (int)($res / 10);
}
while ($carry != 0)
{
array_push($v, $carry % 10);
$carry = (int)($carry / 10);
}
}
function findSumOfDigits($n)
{
$v = array();
array_push($v, 1);
for ($i = 1; $i <= $n; $i++)
multiply($v, $i);
$sum = 0;
$size = count($v);
for ($i = 0 ; $i < $size ; $i++)
$sum += $v[$i];
return $sum;
}
$n = 1000;
print(findSumOfDigits($n));
?>
|
Time complexity: O(n^2) since using multiple loops
Auxiliary space: O(n) because it is using space for vector v
Approach#2: Using for loop
This approach calculates the factorial of the given number using a loop and then finds the sum of its digits by converting the factorial to a string and iterating through each character to add the digit to a running total.
Algorithm
1. Compute the factorial of the given number using any of the previous approaches.
2. Convert the factorial to a string.
3. Traverse through each character in the string and convert it to an integer and add it to the sum variable.
4. Return the sum.
C++
#include <iostream>
#include <string>
#include <vector>
class GFG {
public:
static int sumOfDigitsFactorial(int n)
{
std::vector<int> fact{ 1 };
for (int i = 2; i <= n; ++i) {
multiply(fact, i);
}
int sumOfDigits = 0;
for (int digit : fact) {
sumOfDigits += digit;
}
return sumOfDigits;
}
static void multiply(std::vector<int>& num, int x)
{
int carry = 0;
for (int i = 0; i < num.size() || carry; ++i) {
if (i == num.size()) {
num.push_back(0);
}
long long product
= (long long)num[i] * x + carry;
num[i] = product % 10;
carry = product / 10;
}
}
};
int main()
{
std::cout << "Sum of digits factorial for n=10: "
<< GFG::sumOfDigitsFactorial(10) << std::endl;
std::cout << "Sum of digits factorial for n=100: "
<< GFG::sumOfDigitsFactorial(100)
<< std::endl;
return 0;
}
|
Java
import java.math.BigInteger;
public class GFG {
public static int sumOfDigitsFactorial(int n)
{
BigInteger fact = BigInteger.ONE;
for (BigInteger i = BigInteger.valueOf(2);
i.compareTo(BigInteger.valueOf(n)) <= 0;
i = i.add(BigInteger.ONE)) {
fact = fact.multiply(i);
}
int sumOfDigits = 0;
for (char digit : fact.toString().toCharArray()) {
sumOfDigits += Character.getNumericValue(digit);
}
return sumOfDigits;
}
public static void main(String[] args)
{
System.out.println(
"Sum of digits factorial for n=10: "
+ sumOfDigitsFactorial(10));
System.out.println(
"Sum of digits factorial for n=100: "
+ sumOfDigitsFactorial(100));
}
}
|
Python3
def sum_of_digits_factorial(n):
fact = 1
for i in range(2, n+1):
fact *= i
sum_of_digits = 0
for digit in str(fact):
sum_of_digits += int(digit)
return sum_of_digits
print(sum_of_digits_factorial(10))
print(sum_of_digits_factorial(100))
|
C#
using System;
using System.Collections.Generic;
class GFG {
public static int SumOfDigitsFactorial(int n)
{
List<int> fact = new List<int>{ 1 };
for (int i = 2; i <= n; ++i) {
Multiply(fact, i);
}
int sumOfDigits = 0;
foreach(int digit in fact) { sumOfDigits += digit; }
return sumOfDigits;
}
public static void Multiply(List<int> num, int x)
{
int carry = 0;
for (int i = 0; i < num.Count || carry != 0; ++i) {
if (i == num.Count) {
num.Add(0);
}
long product = (long)num[i] * x + carry;
num[i] = (int)(product % 10);
carry = (int)(product / 10);
}
}
static void Main()
{
Console.WriteLine(
"Sum of digits factorial for n=10: "
+ SumOfDigitsFactorial(10));
Console.WriteLine(
"Sum of digits factorial for n=100: "
+ SumOfDigitsFactorial(100));
}
}
|
Javascript
function sum_of_digits_factorial(n) {
let fact = BigInt(1);
for (let i = 2n; i <= BigInt(n); i++) {
fact *= i;
}
let sum_of_digits = 0;
for (const digit of fact.toString()) {
sum_of_digits += parseInt(digit);
}
return sum_of_digits;
}
console.log(sum_of_digits_factorial(10));
console.log(sum_of_digits_factorial(100));
|
OutputSum of digits factorial for n=10: 27
Sum of digits factorial for n=100: 648
Time complexity: O(n)), where n is the given number
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
26 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...