Program to check for Peterson number
Last Updated :
17 Feb, 2023
A number is said to be a Peterson number if the sum of factorials of each digit of the number is equal to the number itself.
Example:
Input : n = 145
Output = Yes
Explanation:
145 = 5! + 4! + 1!
= 120 + 24 +1
= 145
Input : n = 55
Output : No
Explanation: 5! + 5!
= 120 + 120
= 240
Since 55 is not equal to 240
It is not a Peterson number.
We will pick each digit (Starting from the last digit) of the given number and find its factorial. And add all factorials. Finally, we check if the sum of factorials is equal to number or not.
C++
#include <iostream>
using namespace std;
int fact[10]
= { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 };
bool peterson( int n)
{
int num = n, sum = 0;
while (n > 0) {
int digit = n % 10;
sum += fact[digit];
n = n / 10;
}
return (sum == num);
}
int main()
{
int n = 145;
if (peterson(n))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.util.*;
class GFG
{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
System.out.println( "Enter the number" );
int num=sc.nextInt();
int temp=num;
int f= 1 ,sum= 0 ;
while (num!= 0 )
{
f= 1 ;
int r=num% 10 ;
for ( int i= 1 ;i<=r;i++)
{
f=f*i;
}
sum=sum+f;
num=num/ 10 ;
}
if (sum==temp)
System.out.println( "PETERSON NUMBER" );
else
System.out.println( "NOT PETERSON NUMBER" );
}
}
|
Python3
fact = [ 1 , 1 , 2 , 6 , 24 , 120 , 720 ,
5040 , 40320 , 362880 ]
def peterson(n):
num = n
sum = 0
while n > 0 :
digit = int (n % 10 )
sum + = fact[digit]
n = int (n / 10 )
return ( sum = = num)
n = 145
print ( "Yes" if peterson(n) else "No" )
|
C#
using System;
public class GFG {
static int [] fact
= new int [10] { 1, 1, 2, 6, 24,
120, 720, 5040, 40320, 362880 };
static bool peterson( int n)
{
int num = n;
int sum = 0;
while (n > 0) {
int digit = n % 10;
sum += fact[digit];
n = n / 10;
}
return (sum == num);
}
static public void Main()
{
int n = 145;
if (peterson(n))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
PHP
<?php
$fact = array (1, 1, 2, 6, 24, 120, 720,
5040, 40320, 362880);
function peterson( $n )
{
$num = $n ; $sum = 0;
while ( $n > 0)
{
$digit = $n % 10;
$n = $n / 10;
}
return ( $sum == $num );
}
$n = 145;
if (peterson( $n ))
echo "Yes" ;
else
echo "No" ;
?>
|
Javascript
<script>
let fact = [ 1, 1, 2, 6, 24, 120,
720, 5040, 40320, 362880 ];
function peterson(n)
{
let num = n, sum = 0;
while (n > 0)
{
let digit = n % 10;
sum += fact[digit];
n = parseInt(n / 10);
}
return (sum == num);
}
let n = 145;
if (peterson(n))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: log10(n)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...