From 3f9aae149dba5c9b68ff6f7fd83cadf3fd6b1d7d Mon Sep 17 00:00:00 2001 From: Akshay Dubey <38462415+itsAkshayDubey@users.noreply.github.com> Date: Wed, 9 Nov 2022 21:06:38 +0530 Subject: [PATCH] feat: Add automorphic number implementation (#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> --- maths/automorphic_number.py | 58 +++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 maths/automorphic_number.py diff --git a/maths/automorphic_number.py b/maths/automorphic_number.py new file mode 100644 index 000000000..103fc7301 --- /dev/null +++ b/maths/automorphic_number.py @@ -0,0 +1,58 @@ +""" +== Automorphic Numbers == +A number n is said to be a Automorphic number if +the square of n "ends" in the same digits as n itself. + +Examples of Automorphic Numbers: 0, 1, 5, 6, 25, 76, 376, 625, 9376, 90625, ... +https://en.wikipedia.org/wiki/Automorphic_number +""" + +# Author : Akshay Dubey (https://github.com/itsAkshayDubey) +# Time Complexity : O(log10n) + + +def is_automorphic_number(number: int) -> bool: + """ + # doctest: +NORMALIZE_WHITESPACE + This functions takes an integer number as input. + returns True if the number is automorphic. + >>> is_automorphic_number(-1) + False + >>> is_automorphic_number(0) + True + >>> is_automorphic_number(5) + True + >>> is_automorphic_number(6) + True + >>> is_automorphic_number(7) + False + >>> is_automorphic_number(25) + True + >>> is_automorphic_number(259918212890625) + True + >>> is_automorphic_number(259918212890636) + False + >>> is_automorphic_number(740081787109376) + True + >>> is_automorphic_number(5.0) + Traceback (most recent call last): + ... + TypeError: Input value of [number=5.0] must be an integer + """ + if not isinstance(number, int): + raise TypeError(f"Input value of [number={number}] must be an integer") + if number < 0: + return False + number_square = number * number + while number > 0: + if number % 10 != number_square % 10: + return False + number //= 10 + number_square //= 10 + return True + + +if __name__ == "__main__": + import doctest + + doctest.testmod()