Advertisements
Advertisements
प्रश्न
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 the 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.
कोड लेखन
Advertisements
उत्तर
import java.util.Scanner;
class Trimorphic {
int n;
long cube;
// Constructor to initialise with legal initial values
Trimorphic() {
n = 0;
cube = 0L;
}
// Method to accept a number from the user
void accept() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
n = sc.nextInt();
// Calculate cube and cast to long to prevent overflow
cube = (long) n * n * n;
}
// Recursive method to check if the number matches the ending digits of the cube
boolean check(int num, long c) {
// Base Case: If all digits of num are checked
if (num == 0) {
return true;
}
// If the last digits don't match, it's not Trimorphic
if (num % 10 != c % 10) {
return false;
}
// Recursive call with the remaining digits
return check(num / 10, c / 10);
}
// Method to display the result
void result() {
if (check(n, cube)) {
System.out.println(n + " is a Trimorphic number.");
} else {
System.out.println(n + " is not a Trimorphic number.");
}
System.out.println("Cube of " + n + " is " + cube);
}
// Main function to create an object and run the task
public static void main(String[] args) {
Trimorphic obj = new Trimorphic();
obj.accept();
obj.result();
}
}shaalaa.com
क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
