Special Number ISC Computer Science 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.
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/instance variables:
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 isSpecial(): to check and display if the number 'n' is a special number.
import java.util.Scanner;
class Special{
int n;
public Special(){
n = 0;
}
public Special(int num){
n = num;
}
public void isSpecial(){
int sum = 0;
int f = 1;
for(int i = n; i != 0; i /= 10){
int d = i % 10;
for(int j = 1; j <= d; j++)
f *= j;
sum += f;
f = 1;
}
if(n == sum)
System.out.println("Special number!");
else
System.out.println("Not a special number.");
}
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter the number: ");
int num = Integer.parseInt(in.nextLine());
Special obj = new Special(num);
obj.isSpecial();
}
}
Comments
Post a Comment