Special Number Program In Java

In this tutorial we will see what is a special number , special number example and how to find special number in java . Here , we will write java program take input from user and check given number is special number or not . The special number program frequently asked in Java for academics.

What is a Special Number

A number is said to be special number if the sum of factorial of its digits is equal to the number itself. Special Number Example

145 is a Special Number as 1!+4!+5!=145.

1034 is not  a Special Number as 1!+0!+3!+4! # 1034.

Algorithm to Find Special Number

  1. Take user input and store in number (n).
  2.  Now split the number (n) into digits if the number has more than one digit.
    Find the factorial of each digits.
  3.  Sum up the factorial and store it in a variable sum.
  4. Compare the sum of factorial(sum) to the given number (n).
  5. If the sum of factorial (sum) is equal to the number (n) itself, then given number (n) is a special number, else not.

Special Number In Java

We will implement above algorithm to check given number is special number or not in java . Let’s do code for check  special number in java

import java.util.Scanner;

public class SpecialNumber {
	public static void main(String[] args)
    {
        
        int n, num, r,
        sumOfFactorial = 0;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter number=");
        n = sc.nextInt();
        num = n;
        while (num > 0)
        {
            r = num % 10;
            int fact=1;
            for(int i=1;i<=r;i++)
            {
                fact=fact*i;
            }
            sumOfFactorial = sumOfFactorial+fact;
            num = num / 10;
        }
        if(n==sumOfFactorial)
        {
            System.out.println( n +" is a Special Number" );
        }
        else
        {
            System.out.println(n +"is not Special Number" );
        }
    }

}

Output :

Enter number=145
145 is a Special Number

We leaned about what is a special number and also seen special number example in this tutorial . We have also written program for check given number is special number in java or not . You can see more java program for interview .

Leave a Reply

Your email address will not be published. Required fields are marked *

61 − = 53