Check whether N is a Factorion or not
Given an integer N and the task is to check whether N is a Factorion or not. A Factorion is a number which is equal to the sum of the factorials of its digits.
Examples:
Input: N = 40585
Output: Yes
4! + 0! + 5! + 8! + 5! = 40585
Input: N = 234
Output: No
2! + 3! + 4! = 32
Approach: Create an array fact[] of size 10 to store the factorials of all possible digits where fact[i] stores i!. Now for all the digits of the given number find the sum of factorials of the digits using the fact[] array computed earlier. If the sum if equal to the given number then the number is a Factorion else it is not.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
#define MAX 10
bool isFactorion( int n)
{
int fact[MAX];
fact[0] = 1;
for ( int i = 1; i < MAX; i++)
fact[i] = i * fact[i - 1];
int org = n;
int sum = 0;
while (n > 0) {
int d = n % 10;
sum += fact[d];
n /= 10;
}
if (sum == org)
return true ;
return false ;
}
int main()
{
int n = 40585;
if (isFactorion(n))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
class GFG
{
static int MAX = 10 ;
static boolean isFactorion( int n)
{
int fact[] = new int [MAX];
fact[ 0 ] = 1 ;
for ( int i = 1 ; i < MAX; i++)
fact[i] = i * fact[i - 1 ];
int org = n;
int sum = 0 ;
while (n > 0 )
{
int d = n % 10 ;
sum += fact[d];
n /= 10 ;
}
if (sum == org)
return true ;
return false ;
}
public static void main (String[] args)
{
int n = 40585 ;
if (isFactorion(n))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
MAX = 10
def isFactorion(n) :
fact = [ 0 ] * MAX
fact[ 0 ] = 1
for i in range ( 1 , MAX ) :
fact[i] = i * fact[i - 1 ]
org = n
sum = 0
while (n > 0 ) :
d = n % 10
sum + = fact[d]
n = n / / 10
if ( sum = = org):
return True
return False
n = 40585
if (isFactorion(n)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG
{
static int MAX = 10;
static bool isFactorion( int n)
{
int [] fact = new int [MAX];
fact[0] = 1;
for ( int i = 1; i < MAX; i++)
fact[i] = i * fact[i - 1];
int org = n;
int sum = 0;
while (n > 0)
{
int d = n % 10;
sum += fact[d];
n /= 10;
}
if (sum == org)
return true ;
return false ;
}
public static void Main (String[] args)
{
int n = 40585;
if (isFactorion(n))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
const MAX = 10;
function isFactorion(n)
{
let fact = new Array(MAX);
fact[0] = 1;
for (let i = 1; i < MAX; i++)
fact[i] = i * fact[i - 1];
let org = n;
let sum = 0;
while (n > 0) {
let d = n % 10;
sum += fact[d];
n = parseInt(n / 10);
}
if (sum == org)
return true ;
return false ;
}
let n = 40585;
if (isFactorion(n))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(log10n)
Auxiliary Space: O(MAX)
Last Updated :
13 Mar, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...