Automorphic Number Program in Java

Configurare noua (How To)

Situatie

A number is called an automorphic number if and only if the square of the given number ends with the same number itself. For example, 25, 76 are automorphic numbers because their square is 625 and 5776, respectively and the last two digits of the square represent the number itself. Some other automorphic numbers are 5, 6, 36, 890625, etc.

Backup

  1. public class AutomorphicNumberExample1
  2. {
  3. //user-defined static method that checks whether the number is automorphic or not 
  4. static boolean isAutomorphic(int num)
  5. {
  6. //determines the square of the specified number
  7. int square = num * num;
  8. //comparing the digits until the number becomes 0
  9. while (num > 0)
  10. {
  11. //find the remainder (last digit) of the variable num and square and comparing them
  12. if (num % 10 != square % 10)
  13. //returns false if digits are not equal
  14. return false;
  15. //reduce num and square by dividing them by 10
  16. num = num/10;
  17. square = square/10;
  18. }
  19. return true;
  20. }
  21. //Driver code
  22. public static void main(String args[])
  23. {
  24. //number to be check    
  25. //calling the method and prints the result accordingly
  26. System.out.println(isAutomorphic(76) ? “Automorphic” : “Not Automorphic”);
  27. System.out.println(isAutomorphic(13) ? “Automorphic” : “Not Automorphic”);
  28. }
  29. }

Output 1:

Automorphic
Not Automorphic

Solutie

Tip solutie

Permanent

Voteaza

(15 din 27 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?