C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Special Number Program - Java Programs

Write a program to input a number and print whether the number is a special number or not.
(A number is said to be a special number, if the sum of the factorial of the digits of the number is same as the original number).
Example: 145 is a special number, because 1! + 4! + 5! = 1 + 24 + 120 = 145.
(Where ! stands for factorial of the number and the factorial value of a number is the product of all integers from 1 to that number, example 5! = 1 * 2 * 3 * 4 * 5 = 120)

import java.util.Scanner; class Special{ public static void main(String args[]){ Scanner in = new Scanner(System.in); System.out.print("Enter the number: "); int n = Integer.parseInt(in.nextLine()); int sum = 0; for(int i = n; i != 0; i /= 10) sum += factorial(i % 10); if(n == sum) System.out.println("Special number!"); else System.out.println("Not a special number."); } public static int factorial(int n){ int f = 1; for(int i = 1; i <= n; i++) f *= i; return f; } }

Output

 
 OUTPUT : 
Enter the number: 145
Special number!