Skip to content

fix: integer overflow in MobiusFunction - #7574

Open
SEPURI-SAI-KRISHNA wants to merge 1 commit into
TheAlgorithms:masterfrom
SEPURI-SAI-KRISHNA:fix/mobius-function-integer-overflow
Open

fix: integer overflow in MobiusFunction#7574
SEPURI-SAI-KRISHNA wants to merge 1 commit 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

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 80.43%. Comparing base (346f591) to head (36446d2).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##             master    #7574   +/-   ##
=========================================
  Coverage     80.42%   80.43%           
  Complexity     7460     7460           
=========================================
  Files           815      815           
  Lines         24056    24059    +3     
  Branches       4733     4734    +1     
=========================================
+ Hits          19348    19351    +3     
  Misses         3945     3945           
  Partials        763      763           

☔ 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.

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.

2 participants