(i) Design a class Powerful to check if a given number is powerful or not. A Powerful number is a number which is equal to the sum of its digits, raised to the power of the digit itself.
Example: 3435 = 33 + 44 + 33 + 55 = 27 + 256 + 27 + 3125 = 3435
The details of the members of the class are given below:
Class name: Powerful
Data member/instance variable:
num: to store a positive integer
Methods/Member functions:
Powerful(): constructor to initialize the data member with legal initial value
void input(): to accept a positive integer
int sum(int num): to return the sum of the digitdigit for all digits of num using recursive technique
void check(): to check whether the given number is a powerful number by invoking the function sum() and display the result with an appropriate message
Specify the class Powerful giving details of the constructor, void input(), int sum(int) and void check(). Define the main() function to create an object and call the functions accordingly to enable the task.
import java.util.Scanner;
class Powerful{
int num;
public Powerful(){
num = 0;
}
public void input(){
Scanner in = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
num = Math.abs(in.nextInt());
}
public int sum(int num){
if(num < 10)
return (int)Math.pow(num, num);
int d = num % 10;
return (int)Math.pow(d, d) + sum(num / 10);
}
public void check(){
if(num == sum(num))
System.out.println(num + " is a powerful number!");
else
System.out.println(num + " is not a powerful number.");
}
public static void main(String[] args){
Powerful obj = new Powerful();
obj.input();
obj.check();
}
}
(ii) State the role of base case and recursive case in a recursive method.
The base case is used to end the recursion.
The recursive case repeats itself with simpler version of the problem.