In: Computer Science
Consider the following definition:
A positive integer num is called a factorion if it equals to the
sum of the factorials of its digits.
For example, 145 is a factorion because 1! + 4! + 5! = 1 + 24 + 120
= 145.
Write a program that asks the user to enter a positive integer and
reports if that number is a
factorion or not.
Reminder: the factorial of a positive integer n, denoted by n!, is
the product of all positive
integers less than or equal to n: ?! = ? × (? − 1) × (? − 2) × … ×
2 × 1.
For example, 5! = 5 × 4 × 3 × 2 × 1 = 120
Also, the value of 0! is defined as 1
Your program should interact with the user exactly as demonstrated
in the following two
executions:
Execution example 1:
Please enter a positive integer:
145
145 is a factorion
Code:
#include<iostream>
using namespace std;
int main()
{
int n,j;
cout << "Please enter a positive Integer :
";
cin >> n; //taking input number from user
int dummy=n,sum=0; //storing it in dummy
variable,initialize sum to zero
while (n!=0) //iterate loop till the number is equal
to zero
{
int dig=n%10; //extract each digit
from number
if (dig!=0) //if number!=0 then
calculate factorial of that number
{
int
fact=1;
for
(j=1;j<=dig;j++) //calculate factorial
fact=fact*j;
sum=sum+fact;
//finally add that factorial value to sum
}
else
sum=sum+1; //if
digit is zero then directly add 1 to sum since 0!=1
n=n/10; //divide n with 10 get the
next digits number
}
if (dummy==sum) //finally check if the sum and dummy
are equal then print below
cout << sum << " is a
factorion" << endl;
return 0;
}
Code and Output Screenshots:
Note : if you have any queries please post a comment thanks a lot...