Add Mobius function implementation with comprehensive tests #42
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR implements the Mobius function μ(n) in the mathematical algorithms section, addressing issue #36.
The Mobius function is an important multiplicative function in number theory that returns:
1 if n is a square-free positive integer with an even number of prime factors
-1 if n is a square-free positive integer with an odd number of prime factors
0 if n has a squared prime factor
Closes #36
Changes Made
✅ Added
Algorithms/math/mobius/mobius.py
with efficient O(√n) implementation
✅ Added comprehensive test suite in
Algorithm_tests/math_tests/mobius_test.py
✅ Included detailed docstrings with examples and complexity analysis
✅ Implemented proper input validation and error handling
Implementation Details
The algorithm efficiently computes the Mobius function by:
Handling the special case μ(1) = 1
Checking for prime factor 2 and detecting if it appears more than once
Iterating through odd numbers up to √n to find remaining prime factors
Returning 0 immediately if any prime factor appears more than once (not square-free)
Counting distinct prime factors and returning 1 (even count) or -1 (odd count)
Testing
All 23 test cases pass successfully, covering:
✅ Special cases (μ(1) = 1)
✅ Prime numbers (μ(2), μ(3), μ(17) = -1)
✅ Square-free numbers with 2, 3, 4, and 5 distinct prime factors
✅ Numbers with squared factors (μ(4), μ(12), μ(100) = 0)
✅ Input validation for edge cases (negative, zero, non-integer inputs)
Test Results:
Ran 23 tests in 0.002s
OK
Checklist
✅Code follows the repository's existing style and structure
✅Comprehensive tests included and passing
✅Documentation and docstrings added
✅No breaking changes
✅Branch name follows conventions (mobius)