-
Notifications
You must be signed in to change notification settings - Fork 19.4k
/
AutomorphicNumber.java
67 lines (63 loc) · 2.3 KB
/
AutomorphicNumber.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.thealgorithms.maths;
import java.math.BigInteger;
/**
* <a href="https://en.wikipedia.org/wiki/Automorphic_number">Automorphic Number</a>
* A number is said to be an Automorphic, if it is present in the last digit(s)
* of its square. Example- Let the number be 25, its square is 625. Since,
* 25(The input number) is present in the last two digits of its square(625), it
* is an Automorphic Number.
*/
public final class AutomorphicNumber {
private AutomorphicNumber() {
}
/**
* A function to check if a number is Automorphic number or not
*
* @param n The number to be checked
* @return {@code true} if {@code a} is Automorphic number, otherwise
* {@code false}
*/
public static boolean isAutomorphic(long n) {
if (n < 0) {
return false;
}
long square = n * n; // Calculating square of the number
long t = n;
long numberOfdigits = 0;
while (t > 0) {
numberOfdigits++; // Calculating number of digits in n
t /= 10;
}
long lastDigits = square % (long) Math.pow(10, numberOfdigits); // Extracting last Digits of square
return n == lastDigits;
}
/**
* A function to check if a number is Automorphic number or not by using String functions
*
* @param n The number to be checked
* @return {@code true} if {@code a} is Automorphic number, otherwise
* {@code false}
*/
public static boolean isAutomorphic2(long n) {
if (n < 0) {
return false;
}
long square = n * n; // Calculating square of the number
return String.valueOf(square).endsWith(String.valueOf(n));
}
/**
* A function to check if a number is Automorphic number or not by using BigInteger
*
* @param s The number in String to be checked
* @return {@code true} if {@code a} is Automorphic number, otherwise
* {@code false}
*/
public static boolean isAutomorphic3(String s) {
BigInteger n = new BigInteger(s);
if (n.signum() == -1) {
return false; // if number is negative, return false
}
BigInteger square = n.multiply(n); // Calculating square of the number
return String.valueOf(square).endsWith(String.valueOf(n));
}
}