Skip to content

Commit 4e65832

Browse files
authored
Add pivot integer algorithm in pivot_integer.cpp
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.
1 parent b9c118f commit 4e65832

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

math/pivot_integer.cpp

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* @file pivot_integer.cpp
3+
* @brief Find the pivot integer where the sum of numbers from 1 to x equals the sum from x to n.
4+
*
5+
* This algorithm finds an integer x such that:
6+
* 1 + 2 + ... + x = x + (x+1) + ... + n
7+
*
8+
* The mathematical solution:
9+
* Total sum = n * (n + 1) / 2
10+
* Pivot x exists only if total sum is a perfect square.
11+
*
12+
* @author Aditya
13+
*/
14+
15+
#include <iostream>
16+
#include <cmath>
17+
18+
/**
19+
* @brief Function to compute the pivot integer.
20+
* @param n The upper limit of the range [1, n].
21+
* @return int The pivot integer or -1 if no pivot exists.
22+
*/
23+
int pivot_integer(int n) {
24+
long long total = 1LL * n * (n + 1) / 2;
25+
long long x = sqrt(total);
26+
27+
if (x * x == total)
28+
return (int)x;
29+
30+
return -1;
31+
}
32+
33+
/**
34+
* @brief Main function for demonstration.
35+
*/
36+
int main() {
37+
int n = 8;
38+
std::cout << "Pivot integer for n = " << n << " is: " << pivot_integer(n) << std::endl;
39+
40+
return 0;
41+
}

0 commit comments

Comments
 (0)