#include <cstdlib>
#include<iostream>
#include<cmath>
using namespace std;
int factorial(int f){
int l=1;
for(int i=f;f>0;i--){
l*=f;
f--;
}
return l;}
int number_of_digits(long long n){
int l=0;
while(n>0){
n/=10;
l++;}
return l;
}
int digits(const int z,int i,int n, int q) {
int a[z];
for(int i;i>0;i--){
a[q]=(n%(int)pow(10,i)/(int)pow(10,i-1));
}
return a[q];
}
int main(){
int f,sum=0,q=0;
cin>>f;
while(q<number_of_digits(factorial(f))){
sum+=digits((const int)(factorial(f)),number_of_digits((factorial(f))),factorial(f),q);
q++;}
cout<<sum;
return 0;
}
Hey guys the purpose of this program is to calculate the sum of digits in the factorial of a number, I know it's clumsy I'm a beginner but can you please help me?what's wrong with it?it gave me wrong results.Thank you.
Your function int digits() is not needed. You already have a function that calculates the factorial of the number and one that calculates number of digits, so all you need to do is calculate the factorial of any number you get and find the number of digits in that factorial:
$ ./File
Enter a number: 12
The factorial of the number is 479001600
The number of digits in the factorial is 9
You may also with to make your factorial function be of type long long because your number_of_digits function accepts long long types.
actually the purpose of the function digits is to return each sing digit of the factorial. For an example factorial of 5=120 the function digits will return:
1 2 and 0.
int number_of_digits(longlong n)
{
int l=0;
int f;
int temp;
l = log10(n) + 1;
// OR
// while(n>=1)
// {
// n /= 10;
// l++;
//
// }
f = l;
cout << "The digits in the factorial are: ";
while (f > 0)
{
temp = n / pow(10, f-1);
cout << temp<< ", ";
n -= temp * pow(10, f -1);
--f;
}
cout <<endl;
return l;
}
$ ./File
Enter a number: 12
The factorial of the number is 479001600
The digits in the factorial are: 4, 7, 9, 0, 0, 1, 6, 0, 0,
The number of digits in the factorial is 9
#include<iostream>
#include<cmath>
usingnamespace std;
longlongint factorial(int f)
{
int l;
for(l=1; f>0 ;f--)
l *= f;
return l;
}
/*OR
int factorial(int f)
{
if (f == 1)
return 1;
return f * factorial(f-1);
}*/
int number_of_digits(longlong n)
{
int l=0;
int f;
int temp;
l = log10(n) + 1;
// OR
// while(n>=1)
// {
// n /= 10;
// l++;
//
// }
f = l;
cout << "The digits in the factorial are: ";
while (f > 0)
{
temp = n / pow(10, f-1);
cout << temp<< ", ";
n -= temp * pow(10, f -1);
--f;
}
cout <<endl;
return l;
}
int main()
{
int f;
int sum=0;
int q=0;
cout <<"Enter a number: ";
cin>>f;
cout <<"The factorial of the number is "<< factorial(f) <<endl;
cout<<"The number of digits in the factorial is "<< number_of_digits(factorial(f))<<endl;
return 0;
}