Skip to content

fix: integer overflow in MobiusFunction - #7574

Merged
DenizAltunkapan merged 2 commits into
TheAlgorithms:masterfrom
SEPURI-SAI-KRISHNA:fix/mobius-function-integer-overflow
Aug 19, 2026
Merged

fix: integer overflow in MobiusFunction#7574
DenizAltunkapan merged 2 commits into
TheAlgorithms:masterfrom
SEPURI-SAI-KRISHNA:fix/mobius-function-integer-overflow

Conversation

@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Contributor

Problem

MobiusFunction.mobius decides whether a prime factor is repeated with number % (i * i) == 0, where i is an int. The product overflows for i > 46340, and the wrapped value can still divide number, which makes the method report a squared prime factor that does not exist.

The worst case is Integer.MAX_VALUE, whose square wraps to exactly 1. Since every number is divisible by 1, the method returns 0 for it:

MobiusFunction.mobius(2147483647);  // returns 0, expected -1 (2147483647 is prime)

Separately, the loop for (int i = 1; i <= number; i++) calls PrimeCheck.isPrime(i) on every value up to number, so the method is O(n * sqrt(n)). mobius(2147483647) performs on the order of 2^31 iterations, each with a primality check.

Fix

Replaced the scan over all candidates with ordinary trial division that divides each prime factor out of a running remainder:

  • the loop bound is (long) factor * factor <= remaining, widened to long so it cannot overflow near Integer.MAX_VALUE;
  • a factor found twice in a row means a squared prime factor, so the method returns 0;
  • whatever remains after the loop is either 1 or a single prime larger than the square root, and is counted once.

This removes the overflow and drops the complexity from O(n * sqrt(n)) to O(sqrt(n))mobius(Integer.MAX_VALUE) now returns immediately. The explicit number == 1 early return is no longer needed: the loop does not execute and the factor count of 0 yields 1, which is the same result.

Behaviour is otherwise unchanged, including the IllegalArgumentException for non-positive input.

Tests

MobiusFunctionTest previously only checked 1..100, all of which are well below the overflow threshold. Added a parameterized case over large inputs, including Integer.MAX_VALUE and its neighbours, perfect powers of two, 46340^2 and large primes. mobius(2147483647) fails on the old code.

  • I have read CONTRIBUTING.md.
  • This pull request is all my own work -- I have not plagiarized it.
  • All filenames are in PascalCase.
  • All functions and variable names follow Java naming conventions.
  • All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
  • All new algorithms include a corresponding test class that validates their functionality.
  • All new code is formatted with clang-format -i --style=file path/to/your/file.java

@codecov-commenter

codecov-commenter commented Aug 15, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 80.58%. Comparing base (56e2699) to head (d84a5a5).

Additional details and impacted files
@@             Coverage Diff              @@
##             master    #7574      +/-   ##
============================================
- Coverage     80.59%   80.58%   -0.01%     
+ Complexity     7483     7481       -2     
============================================
  Files           815      815              
  Lines         24060    24062       +2     
  Branches       4736     4736              
============================================
+ Hits          19390    19391       +1     
  Misses         3907     3907              
- Partials        763      764       +1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@DenizAltunkapan
DenizAltunkapan enabled auto-merge (squash) August 19, 2026 08:43
@DenizAltunkapan
DenizAltunkapan merged commit 3ddd052 into TheAlgorithms:master Aug 19, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants