calculate sum of factorials of digits of a 3 digit number

0

I have written this c++ code to calculate the sum of factorial of digits in a three digit number but its not working:

output is:

Process returned -1073741571 (0xC00000FD) execution time : 9.337 s Press any key to continue.

#include <iostream>
#include <exception>
using namespace std;
unsigned fact(int n)
{
    if (n == 1|n==0)
        return 1;
    else
        return n * fact(n - 1);
}
int main()
{
    int num;
    int sum=0;
    int tmp;
    cout<<"Enter 3 digit number:\n";
    cin>>num;
    if(num<99|num>999)
    {
        cout<<"Not a 3 digit number!";
        return (1);
    }
    tmp = num%100;
    sum = sum+ fact(tmp);
    tmp = num%10;
    sum = sum+ fact(tmp);
    tmp = num%1;
    sum = sum+ fact(tmp);

cout<<"Sum of factorial of digits in a number:"<<sum;
return(0);
}
c++
factorial
asked on Stack Overflow Apr 22, 2019 by j doe • edited Apr 22, 2019 by j doe

2 Answers

1

The digits of num are not num % 100, num % 10, and num % 1. Whatever gave you that idea?

Take for instance num=567. Then we have

num % 100 = 67

num % 10 = 7

num % 1 = 0

You need to think about it a bit more.

answered on Stack Overflow Apr 22, 2019 by TonyK
0

I forgot how to select digits of a number this works now:

#include <iostream>
#include <exception>
using namespace std;
unsigned fact(int n)
{
    if (n == 1||n==0)
        return 1;
    else
        return n * fact(n - 1);
}
int main()
{
    int num;
    int sum=0;
    int tmp;
    cout<<"Enter 3 digit number:\n";
    cin>>num;
    if(num<=99|num>999)
    {
        cout<<"Not a 3 digit number!";
        return (1);
    }
    tmp = num%10;
    sum = sum+ fact(tmp);
    tmp = num/10%10;
    sum = sum+ fact(tmp);
    tmp = num/100%10;
    sum = sum+ fact(tmp);

cout<<"Sum of factorial of digits in a number:"<<sum;
return(0);
}
answered on Stack Overflow Apr 22, 2019 by j doe

User contributions licensed under CC BY-SA 3.0