Sum Of Digits Of A Simple Factorial

Tell me any other shorter method for this program-
#include< iostream>
#include< conio.h>
using namespace std;

float f=1,n;

void fact(float );

void sum(float );

int main()

{

int t,i;


	scanf("%f",&n);

	fact(n);

	sum(f);


getch();

return 0;	

}

void fact(float n)

{

int i;	

for(i=1;i<=n;i++)

{

	(float)f*=i;

}	 	

}

void sum(float f)

{

int i,rev=0;	

for(i=0;f/10>0;i++)

{

	rev+=(((int)f%10));

	f/=10;

}

printf("%d",rev);

}

Brother this code is in python,

Since Python has big num data types also inbuilt functions it is very easy to compute sum of digits in factorial of n,
In this eample n = 2000

Here is a sample code

from math import factorial

#Store factorial of 2000 in a variable a
a=factorial(2000)

#Typecast variable to string
a=str(a)

#print a

#initialize a counter variable to add all numbers, to 0
add=0

#Iterate through the string a, i.e. factorial of 2000
for i in a:
    #Add each value after typecasting character into integer
    add+=int(i)

#Print sum of digits in factorial(2000)
print add
And thats it..!!

from math import factorial
b=factorial(20)
c=str(b)
sum=0
for i in c:
sum+=int(i)
print sum

1 Like

Storing each digit of the factorial in an integer array will be helpful,because then it will be an easy task to add all the digits. Following code will give you sum of digits of factorial for 1< n< 2000

    #include< iostream >
using namespace std;
int sumoffactdigits(int n)
{	int m=1,temp=0,i,j,sum=0,x;
	int a[7000];
	a[1]=1;
	//storing digits in array
	for(i=1;i<=n;i++)
	{
		for(j=1;j<=m;j++)
		{
			 x=a[j]*i+temp;
			a[j]=x%10;
			temp=x/10;
		}
		while(temp!=0)
		{
			m=m+1;
			a[m]=temp%10;
			temp/=10;
		}
	}
	for(i=m;i>=1;i--)
	{
		sum+=a[i];
	}
	return sum;
	
}
int main()
{ int y;
cin>>y;
cout<< sumoffactdigits(y)<< "\n";
return 0;}
1 Like

Well, if the requirement is being short, you can do it in one line in python (excluding an import and an input read that could be placed in the one liner)

from math import factorial

n = int(raw_input())  # input n

print sum(int(c) for c in str(factorial(n)))

can anyone post link of this question…

Thanks @chashmeet

1 Like