Skip to content

Add Kaprekar number checker to special_numbers #12723

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 14 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Clarified Kaprekar number definition and excluded powers of 10 (e.g.,…
… 10, 100)
  • Loading branch information
Sean-Randall committed May 12, 2025
commit e523f998bd95aba96c4a814f46d94280484e4e41
24 changes: 13 additions & 11 deletions maths/special_numbers/kaprekar_number.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
def is_kaprekar_number(n: int) -> bool:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: n

"""
Determine whether a number is a Kaprekar number.
Determine whether a number is a Kaprekar number (excluding powers of 10).

A Kaprekar number is one where the square can be split into parts
that sum to the original number.
A Kaprekar number is a positive number n such that:
n^2 = q * 10^m + r, for some m >= 1, q >= 0, 0 <= r < 10^m,
and n = q + r, with the restriction that n is not a power of 10.

Args:
n (int): The number to check.
Expand All @@ -18,18 +19,19 @@ def is_kaprekar_number(n: int) -> bool:
True
>>> is_kaprekar_number(10)
False
>>> is_kaprekar_number(1)
True
"""
square = str(n**2)
if n == 1:
return True
if n <= 0 or (n % 10 == 0 and n == 10 ** len(str(n))):
return False # Disallow powers of 10 (e.g., 10, 100)

square = str(n ** 2)
for i in range(1, len(square)):
left, right = square[:i], square[i:]
if int(right) == 0:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems this check is not needed anymore.

continue
if n == int(left or "0") + int(right):
return True
return n == 1


if __name__ == "__main__":
import doctest

doctest.testmod()
return False