Articles

C++ program to check a Peterson number

C++ program to check a Peterson number

In this chapter of C++ program tutorial out task is: 

  • write a c++ program to check whether a number is peterson number or not

C++ program to check a number is Peterson number or not

Below is the C++ program to check if a number is Peterson number or not.

/*  Program Name : To check whether a number is Peterson or not
    Program Author : Sayantan Bose
*/

#include <iostream>
#include <math.h>
using namespace std;

//This function will return the sum of the factorials of each digit of the inputed number.
int peter(int num)
{
    int r,sum=0,f=1,i;

    while(num!=0)
    {
        r=num%10;
        for(i=1;i<=r;i++)
        f=f*i;
        sum=sum+f;
        f=1;
        num=num/10;

    }
    return sum;
}

// This is the main function

int main() {

int num,sum=0;
 cout<<"Enter any number to check Peterson:\n";
   cin>>num;
    int new_num;
    new_num=num;
 sum=peter(num);
  if(sum==new_num)
        cout<<num<<" is a Peterson number";
    else
        cout<<num<< " is not a Peterson number";

	return 0;
}


OUTPUT
Enter the number to check Peterson:
145
145 is an Peterson number
Or
Enter the number to check Peterson:
53
53 is not an Peterson number
 
 
EXPLANATION :
In the above c++ program to check if a number is Peterson or not:
  • A number is said to be Peterson if and only if the sum of the factorial of each digit of the number is equal to the number itself.
  • For example: 145 is a Peterson number. Because 145 can be written as the sum of 1!+4!+5!, is equal to 145 which is the number itself.
  • In the method peter, we are calculating the sum of the factorial of each digit of the number . And then the sum is returned to the main method.
  • In the main method the sum is then compared with the original number provided as input.
  • If both of them turn out to be equal the number is a Peterson number else it isn't.

You can see the above code execution and output in codeblocks IDE:

 


CPP Programs

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Sayantan Bose
- šŸ”­ Iā€™m currently working on DS Algo skills - šŸŒ± Iā€™m currently learning web develeopement - šŸ‘Æ Iā€™m looking to collaborate with Oppia - šŸ“« Reach me at https://www.linkedin.com/in/sayantan-bose-14134a1a6/ - šŸ˜„ Pronouns: his/him
Page Views :    Published Date : Dec 11,2020  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!