Skip to content

fix(maths): use math.isqrt in perfect_square instead of float sqrt - #15766

Open
divya0795 wants to merge 1 commit into
TheAlgorithms:masterfrom
divya0795:fix-perfect-square-isqrt
Open

divya0795 wants to merge 1 commit into
TheAlgorithms:masterfrom
divya0795:fix-perfect-square-isqrt

Conversation

@divya0795

Copy link
Copy Markdown

Describe your change

  • Add an algorithm?
  • Fix a bug or typo in an existing algorithm?
  • Add or change doctests? -- Note: Please avoid changing both code and tests in a single pull request.
  • Documentation change?

Problem

maths/perfect_square.py perfect_square() decides squareness with floats:

return math.sqrt(num) * math.sqrt(num) == num

The product of two rounded square roots often rounds back to exactly num, so many non-squares are reported as squares. Above 2**53 the float root loses precision and real squares are missed, and any negative input raises ValueError from math.sqrt instead of returning False.

Reproduced on free-threaded CPython 3.15.2 (the version in .python-version) at 30507bb:

>>> math.sqrt(11) * math.sqrt(11) == 11
True
>>> perfect_square(11), perfect_square(14), perfect_square(17)
(True, True, True)
>>> perfect_square((2**30 + 1) ** 2)
False
>>> perfect_square(-4)
ValueError: expected a nonnegative input, got -4.0

Over 0..999, 513 non-squares come back True (11, 14, 17, 21, 22, 27, 30, ...). Over 0..20000, 10,369 do.

Fix

Use the exact integer square root, which needs no float rounding:

return num >= 0 and math.isqrt(num) ** 2 == num

This is a code-only change. The existing doctests (9, 16, 1, 0 → True; 10 → False) are untouched and still pass. perfect_square_binary_search() in the same file is not changed.

Behaviour change, checked against master

input master this PR
11, 14, 17 True False
(2**30 + 1) ** 2 False True
-4 ValueError False
0, 1, 9, 16, 10 unchanged unchanged

Swept -50..20000, 300 squares near 2**52, plus (2**53 + 1) ** 2, 10**16 + 1 and (10**20 + 7) ** 2: every changed output was a wrong answer on master, and the patched function agrees with math.isqrt(n) ** 2 == n on all of them.

One more change: a float argument (the signature is num: int) now raises TypeError from math.isqrt instead of being compared as a float, so perfect_square(2.25) no longer returns True.

Validation (free-threaded CPython 3.15.2, macOS arm64)

  • A local regression test (11 and 14 → False, all of 0..9999 against math.isqrt, (2**30 + 1) ** 2 → True, -4 → False) fails on master and passes with this change. I kept it out of this PR because AGENTS.md asks not to change code and its doctests in the same PR. I can open the doctests as a follow-up PR if that helps.
  • uv run --with=pytest-run-parallel pytest --iterations=8 --parallel-threads=auto --ignore-gil-enabled maths/perfect_square.py: all pass.
  • The full CI pytest command from build.yml gives the same result as on master (4139 passed, plus the same 2 environment-dependent failures as master on macOS: the gaussian_distribution RNG doctest and the network-dependent instagram_crawler doctest).
  • uvx pre-commit run --files maths/perfect_square.py: all hooks pass. uvx ruff check .: all checks passed.

Checklist

  • I have read CONTRIBUTING.md.
  • This pull request is all my own work -- I have not plagiarized.
  • I know that pull requests will not be merged if they fail the automated tests.
  • This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
  • All new Python files are placed inside an existing directory.
  • All filenames are in all lowercase characters with no spaces or dashes.
  • All functions and variable names follow Python naming conventions.
  • All function parameters and return values are annotated with Python type hints.
  • All functions have doctests that pass the automated testing.
  • All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
  • If this pull request resolves one or more open issues, then the description above includes the issue number(s) with a closing keyword: "Fixes #ISSUE-NUMBER".

🤖 Generated with Claude Code

math.sqrt(num) * math.sqrt(num) == num reports many non-squares as squares (11, 14, 17, ...), misses squares above 2**53 and raises ValueError for negative input. Compare the exact integer square root instead.
@algorithms-keeper algorithms-keeper Bot added awaiting reviews This PR is ready to be reviewed enhancement This PR modified some existing files labels Nov 17, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting reviews This PR is ready to be reviewed enhancement This PR modified some existing files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant