Trimorphic Numbers in Java

In previous section, we have discussed many numbers programs that are usually asked in interviews. In this section, we are going to discuss what is trimorphic number and how to check if the number is trimorphic or not.

Trimorphic Number

A number T is said to be trimorphic if the cube of T (T*T*T or T3) terminates with T. Let's understand it with the help of examples.

Example 1:

Input:

T = 501

Output:

501 is a trimorphic number.

Explanation: If we multiply 501 by itself 3 times (501 x 501 x 501), we get 125751501, and 125751501 ends with the number 501. Hence, 501 is the trimorphic number.

Example 2:

Input:

T = 7

Output:

7 is not a trimorphic number.

Explanation: If we multiply 7 by itself 3 times (7 x 7 x 7), we get 343, and 343 does not end with the number 7. Hence, 7 is not the trimorphic number.

Algorithm

Step1: Take a number T and find its cube. Let's assume that T3 = Y.

Step 2: Find the number of digits present in the number T. Let's assume there is n number of digits present in the number T.

Step 3: Find the value of 10n. Assume that the value of 10n is p.

Step 4: Compute the value of Y - T. Let's say Y - T = r

Step 5: Check whether the value of r % p is equal to 0 or not. If the value is 0, then T is a trimorphic number; otherwise, not.

Trimorphic Number Java Program

Let's implement the above algorithm in a Java program.

FileName: TrimorphicNumber.java

Output:

1 is a trimorphic number.
2 is not a trimorphic number.
3 is not a trimorphic number.
4 is a trimorphic number.
5 is a trimorphic number.
6 is a trimorphic number.
7 is not a trimorphic number.
8 is not a trimorphic number.
9 is a trimorphic number.
10 is not a trimorphic number.

In the above program, we have to do a few things separately. For example, we have to compute the power. Also, the total number of digits present in the number T. If we use string, we can avoid these mentioned operations. Let's find it out in the following program.

FileName: TrimorphicNumber1.java

Output:

1 is a trimorphic number.
2 is not a trimorphic number.
3 is not a trimorphic number.
4 is a trimorphic number.
5 is a trimorphic number.
6 is a trimorphic number.
7 is not a trimorphic number.
8 is not a trimorphic number.
9 is a trimorphic number.
10 is not a trimorphic number.