Special Number ISC 2008 Theory

A special number is a number in which the sum of the factorial of each digit is equal to the number itself.

For example: 145.
1! + 4! + 5! = 1 + 24 + 120 = 145.
Thus, 145 is a special number.

Design a class Special to check if a given number is a special number. Some of the members of the class are given below:

Class name: Special
Data members:
n: to store the integer.
Member functions:
Special(): constructor to assign 0 to n.
Special(int): parameterized constructor to assign a value to ‘n’.
void sum(): calculate and display the sum of the first and last digit of ‘n’.
void isSpecial(): check and display if the number ‘n’ is a special number.

Specify the class Special giving details of the constructors, void sum() and void isSpecial(). You need not write the main() function.

class Special{
    private int n;
    public Special(){
        n = 0;
    }
    public Special(int num){
        n = num;
    }
    public void sum(){
        int sum = 0;
        String s = Integer.toString(n);
        String first = s.substring(0, 1);
        String last = s.substring(s.length() - 1);
        sum = Integer.parseInt(first) + Integer.parseInt(last);
        System.out.println("Sum of first and last digit: " + sum);
    }
    public void isSpecial(){
        int num = n;
        int sum = 0;
        while(num != 0){
            int d = num % 10;
            int f = 1;
            for(int i = 1; i <= d; i++)
                f *= i;
            sum += f;
            num /= 10;
        }
        if(n == sum)
            System.out.println(n + " is a special number.");
        else
            System.out.println(n + " is not a special number.");
    }
}

To find the factorial of each digit using recursion, you may create the following method:

int factorial(int x){
    if(x <= 1)
        return 1;
    return x * factorial(x - 1);
}

Leave a Reply