‹ Back to the paper
Question 7(i)
8 marks
Computer ScienceISC 2026 Computer Science Paper 1ProgramRecursion
Write the program described below.
A class Trimorphic has been defined to accept a positive integer from the user and display if it is…
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: $24^3 = 13824$ ends with 24
Example 2: $5^3 = 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(int, long) and void result( ). Define the main( ) function to create an object and call the functions accordingly to enable the task.
Answer
Answer
import java.util.Scanner;
class Trimorphic
{
int n;
long cube;
Trimorphic()
{
n = 0;
cube = 0L;
}
void accept()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
n = sc.nextInt();
cube = (long) n * n * n;
}
boolean check(int num, long c)
{
if (num == 0)
return true;
if (num % 10 != c % 10)
return false;
return check(num / 10, c / 10);
}
void result()
{
if (check(n, cube))
System.out.println(n + " is a Trimorphic number.");
else
System.out.println(n + " is not a Trimorphic number.");
}
public static void main(String[] args)
{
Trimorphic obj = new Trimorphic();
obj.accept();
obj.result();
}
}Explanation: The constructor initialises n and cube. accept() inputs a positive integer and calculates its cube. check(num, c) recursively compares the last digits of num and c; if num becomes 0, all digits matched and it returns true, otherwise if any pair of digits differ it returns false. result() calls check() and displays the message.