Optimize Factorial Algorithm (Iterative Implementation) and Add Comprehensive JUnit Test Suite
Summary
This PR improves the existing Factorial implementation in the divideandconquer package by replacing the recursive algorithm with an optimized iterative version. The new implementation reduces space complexity, avoids recursion overhead, and prevents stack overflow for moderately large inputs.
In addition, this PR adds a comprehensive JUnit test suite to validate correctness, edge cases, performance behavior, and relative improvement compared to the original recursive approach.
✔ Algorithm Improvements
- Replaced recursive factorial implementation with iterative approach
- Eliminated O(n) recursive stack usage → now O(1) space complexity
- Improved execution time by removing recursion overhead
- Fully maintains expected mathematical behavior for all valid inputs
- Safer for moderately large values (e.g., 15!, 20!) compared to recursion
✔ Test Suite Added (FactorialTest.java)
The added JUnit test suite covers:
1. Basic Correctness
- factorial(5) → 120
- factorial(0) → 1
- Negative inputs throw
IllegalArgumentException
2. Performance & Analysis
- Benchmarks factorial(15)
- Validates timing constraints and expected performance characteristics
3. Demonstrating Algorithmic Improvement
- Contains a local copy of the original recursive method for comparison
- Shows iterative version is faster in practice
- Confirms iterative algorithm handles larger inputs safely without stack overflow
Why This PR Is Valuable
- Improves algorithmic quality and safety
- Adds missing test coverage for educational clarity
- Matches project philosophy of readable, practical algorithm implementations
- Clean, minimal changes limited to relevant files only
- Helps future learners compare recursion vs iteration in factorial computation
Thank you for reviewing this contribution!
Codecov Report
:white_check_mark: All modified and coverable lines are covered by tests.
:white_check_mark: Project coverage is 78.91%. Comparing base (d9f2ac8) to head (9041247).
Additional details and impacted files
@@ Coverage Diff @@
## master #7145 +/- ##
=========================================
Coverage 78.90% 78.91%
+ Complexity 6853 6850 -3
=========================================
Files 769 768 -1
Lines 22668 22665 -3
Branches 4456 4455 -1
=========================================
- Hits 17887 17885 -2
Misses 4067 4067
+ Partials 714 713 -1
:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.
:rocket: New features to boost your workflow:
- :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
All CI checks have passed. Formatting has been applied using clang-format. Please review the PR.