Skip to content

Commit 3f9aae1

Browse files
feat: Add automorphic number implementation (TheAlgorithms#7978)
* feat: Add automorphic number implementation * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * refactor: Add type checking for number * refactor: Rename variable n to number * test: Add doctest * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * test: Add unit test for number=0 Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 8951d85 commit 3f9aae1

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

maths/automorphic_number.py

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
"""
2+
== Automorphic Numbers ==
3+
A number n is said to be a Automorphic number if
4+
the square of n "ends" in the same digits as n itself.
5+
6+
Examples of Automorphic Numbers: 0, 1, 5, 6, 25, 76, 376, 625, 9376, 90625, ...
7+
https://en.wikipedia.org/wiki/Automorphic_number
8+
"""
9+
10+
# Author : Akshay Dubey (https://github.com/itsAkshayDubey)
11+
# Time Complexity : O(log10n)
12+
13+
14+
def is_automorphic_number(number: int) -> bool:
15+
"""
16+
# doctest: +NORMALIZE_WHITESPACE
17+
This functions takes an integer number as input.
18+
returns True if the number is automorphic.
19+
>>> is_automorphic_number(-1)
20+
False
21+
>>> is_automorphic_number(0)
22+
True
23+
>>> is_automorphic_number(5)
24+
True
25+
>>> is_automorphic_number(6)
26+
True
27+
>>> is_automorphic_number(7)
28+
False
29+
>>> is_automorphic_number(25)
30+
True
31+
>>> is_automorphic_number(259918212890625)
32+
True
33+
>>> is_automorphic_number(259918212890636)
34+
False
35+
>>> is_automorphic_number(740081787109376)
36+
True
37+
>>> is_automorphic_number(5.0)
38+
Traceback (most recent call last):
39+
...
40+
TypeError: Input value of [number=5.0] must be an integer
41+
"""
42+
if not isinstance(number, int):
43+
raise TypeError(f"Input value of [number={number}] must be an integer")
44+
if number < 0:
45+
return False
46+
number_square = number * number
47+
while number > 0:
48+
if number % 10 != number_square % 10:
49+
return False
50+
number //= 10
51+
number_square //= 10
52+
return True
53+
54+
55+
if __name__ == "__main__":
56+
import doctest
57+
58+
doctest.testmod()

0 commit comments

Comments
 (0)