Write a program in Java to accept a number from the user. Display next 3 Automorphic number. Method: void accept(int ) : Acept a number and generate next 3 Automorphic number. Plese help . And please don't give wrong answer intentionally please. It felt bad.:"(
Answers
Solution:
The given problem is solved using language - Java.
import java.util.Scanner;
public class Automorphic{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
Automorphic object = new Automorphic();
object.accept(sc.nextInt());
}
void accept(int n){
System.out.println("You entered: " + n);
System.out.println("The next three automorphic number after " + n + " are..");
int c = 1;
while(c<4){
if(isAutomorphic(++n)){
System.out.print(n + " ");
c++;
}
}
}
static boolean isAutomorphic(int n){
int sq = n * n;
String num = Integer.toString(n);
String square = Integer.toString(sq);
return square.endsWith(num);
}
}
Explanation:
Automorphic Number: A number is said to be an Automorphic Number if its square ends with the number itself. Example: 5 is an automorphic number since its square 25 also ends with 5
Logic To Check Automorphic Number:
(1) At first, calculate the square of the number.
(2) Now, convert both the number and its square to string.
(3) There is a function in String class named endsWith() that check whether a string ends with specific set of characters or not. We can easily check using this function.
To display the next three automorphic number,
(1) Create a counter variable with initial value = 1.
(2) Initialise a loop.
(3) Start checking from the number next to the entered number.
(4) Check if the number is automorphic.
(5) If true, display the number. At the same time, increment the counter variable.
(6) When the value of the counter variable becomes 4, the loop terminates since the next three automorphic numbers are displayed.
See attachment for output.