Add pivot integer algorithm in pivot_integer.cpp #3068
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.
Implement an algorithm to find the pivot integer where the sum of numbers from 1 to x equals the sum from x to n.
The function returns the pivot integer or -1 if no pivot exists.
Description of Change
This PR adds a new implementation of the Pivot Integer problem inside the math directory.
The algorithm determines whether there exists an integer x such that:
1 + 2 + … + x = x + (x+1) + … + n
Using the mathematical property that a pivot exists only when the total sum of the first n natural numbers is a perfect square, the solution computes the pivot in O(1) time.
A small demonstration main() function is included for testing.
Checklist
• Added description of change
• File name follows guidelines (pivot_integer.cpp)
• Added test/example in main(), test passes
• Added clear documentation following Doxygen style
• Added relevant inline comments
• PR title follows semantic commit guidelines
• Searched for duplicates
• I acknowledge that all my contributions are made under the project’s license
Notes
Adds a clean, optimized, and well-documented math utility for computing the pivot integer.