Peterson Number in Java

Configurare noua (How To)

Situatie

Backup

Peterson Number

A number is said to be Peterson if the sum of factorials of each digit is equal to the sum of the number itself.

Steps to Find Peterson Number
  • Read or initialize a number (n).
  • Find the last digit (d) of the given number.
  • Find the factorial (fact) of the digit.
  • Add the factorial (fact) to a variable
  • Repeat steps 2 to 4 until the given number becomes 0.
  • Compare the sum with n. If both are equal, the given number is Peterson, else not.
Example of Peterson Number

Suppose, we have to check the number (n) 145 is Peterson or not.

Number = 145

145 = !1 + !4 + !5

=1+4*3*2*1+5*4*3*2*1

=1+24+120

145=145

Solutie

  1. import java.io.*;
  2. import java.util.*;
  3. public class PetersonNumberExample1
  4. {
  5. //an array is defined for the quickly find the factorial
  6. static long[] factorial = new int[] { 112624120720504040320362880362880039916800479001600};
  7. //driver code
  8. public static void main(String args[])
  9. {
  10. //constructor of the Scanner class
  11. Scanner sc = new Scanner(System.in);
  12. System.out.print(“Enter a number to check: “);
  13. //reading a number from the user
  14. int n=sc.nextInt();
  15. //calling the user-defined function to check Peterson number
  16. if (isPeterson(n))
  17. System.out.println(“The given number is a Peterson number.”);
  18. else
  19. System.out.println(“The given number is not a Peterson number.”);
  20. }
  21. //function to check the given number is Peterson or not
  22. static boolean isPeterson(int n)
  23. {
  24. int num = n;
  25. int sum = 0;
  26. //loop executes until the condition becomes false
  27. while (n > 0)
  28. {
  29. //determines the last digit of the given number    
  30. int digit = n % 10;
  31. //determines the factorial of the digit and add it to the variable sum
  32. sum += factorial[digit];
  33. //removes the last digit of the given number
  34. n = n / 10;
  35. }
  36. //compares sum with num if they are equal returns the number itself
  37. return (sum == num);
  38. }
  39. }

Output 1:

Enter a number to check: 145
The given number is a Peterson number.

Output 2:

Enter a number to check: 773
The given number is not a Peterson number.

Tip solutie

Permanent

Voteaza

(11 din 19 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?