Prashnikaप्रश्निका
Code
About
‹ Back to the paper

Question 9

10 marks

Computer ScienceISC 2020 Specimen Computer Science Paper 1ProgramObjects

Write the program described below.

A Special number is a number in which the sum of the factorial of its digits is equal to the…

A Special number is a number in which the sum of the factorial of its digits is equal to the number. Example: 145 ($1! + 4! + 5! = 145$). Thus, 145 is a Special number. Design a class Special to check if the given number is a Special number or not. Some of the members of the class are given below: Class name : Special Data member/instance variable: n : integer to store number Member functions/methods: Special() : default constructor void read() : to accept the number int factorial(int x) : return the factorial of a number using recursive technique boolean isSpecial() : checks for the special number by invoking the function factorial() and returns true if Special, otherwise returns false void display() : displays the result with an appropriate message Specify the class Special, giving details of the Constructor, void read(), int factorial(int), boolean isSpecial() and void display(). Define the main() function to create an object and call the member function according to enable the task.
Read the note: ISC Practicals and Theory - Factorial

Answer

Answer

import java.util.Scanner;

class Special
{
    int n;

    Special()
    {
        n = 0;
    }

    void read()
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        n = sc.nextInt();
    }

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

    boolean isSpecial()
    {
        int sum = 0, t = n;
        while (t > 0)
        {
            sum = sum + factorial(t % 10);
            t = t / 10;
        }
        return sum == n;
    }

    void display()
    {
        if (isSpecial())
            System.out.println(n + " is a Special number");
        else
            System.out.println(n + " is not a Special number");
    }

    public static void main(String args[])
    {
        Special ob = new Special();
        ob.read();
        ob.display();
    }
}
Explanation: The constructor sets n to 0 and read() accepts the number. factorial(x) is recursive: it returns 1 when x <= 1 (base case), otherwise x * factorial(x - 1). isSpecial() extracts each digit of n with % 10 and / 10, adds the factorial of each digit and returns true if the sum equals n. display() prints an appropriate message. Tested: 145 gives 145 is a Special number (1! + 4! + 5! = 1 + 24 + 120 = 145).