(i) A class Trimorphic has been defined to accept a positive integer from the user and display if it is a Trimorphic number or not.
A number is said to be Trimorphic if the cube of the number ends with the number itself.
Example 1: 243 = 13824 ends with 24
Example 2: 53 = 125 ends with 5
The details of the members of the class are given below:
Class name: Trimorphic
Data members/instance variables:
n: to store the number
cube: to store the cube of the number
Methods/Member functions:
Trimorphic(): constructor to initialise the data members with legal initial values
void accept(): to accept a number
boolean check(int num, long c): to compare num with the ending digits of c using recursive technique
void result(): to check whether the given number is a trimorphic number by invoking the function check() and to display an appropriate message.
Specify the class Trimorphic giving the details of the constructor, void accept(), boolean check() and void result(). Define the main() function to create an object and call the functions accordingly to enable the task.
import java.util.Scanner;
class Trimorphic{
private int n;
private long cube;
public Trimorphic(){
n = 0;
cube = 0L;
}
public void accept(){
Scanner in = new Scanner(System.in);
System.out.print("Enter the number: ");
n = in.nextInt();
cube = (long)Math.pow(n, 3);
}
public boolean check(int num, long c){
if(num == c)
return true;
String n = String.valueOf(num);
String cube = String.valueOf(c);
if(n.length() == cube.length())
return false;
c = Long.parseLong(cube.substring(1));
return check(num, c);
}
public void result(){
if(check(n, cube))
System.out.println(n + " is Trimorphic!");
else
System.out.println(n + " is not Trimorphic.");
}
public static void main(String[] args){
Trimorphic obj = new Trimorphic();
obj.accept();
obj.result();
}
}
(ii) State any two differences between iteration and recursion.
a) Iteration uses less memory whereas recursion uses more memory.
b) Iteration stops when the loop condition becomes false, whereas recursion stops when the base case is reached.