Sponsored
Sponsored
This approach involves iterating through each number from 1 to n and checking if it satisfies the given condition of a pivot integer. For each candidate pivot integer x, calculate the sum of numbers from 1 to x using the formula for the sum of an arithmetic series. Similarly, calculate the sum from x to n. Compare these sums to determine if x is a pivot integer.
Time Complexity: O(n).
Space Complexity: O(1).
1public class PivotFinder {
2 public static int findPivot(int n) {
3 for (int x = 1; x <= n; ++x) {
4 int sum1 = x * (x + 1) / 2;
5 int sum2 = (n * (n + 1) / 2) - ((x - 1) * x / 2);
6 if (sum1 == sum2) return x;
7 }
8 return -1;
9 }
10
11 public static void main(String[] args) {
12 int n = 8;
13 System.out.println(findPivot(n));
14 }
15}
In Java, the solution uses a similar logic. The for-loop checks each x value, calculating the sums using the provided formulas and checking for equality to determine the pivot.
Instead of iterating through each possible x, we can use mathematical formulation. As the sum from 1 to n is fixed, let's denote the total sum as S. Then, for pivot x, the condition becomes:
(x * (x + 1)) / 2 = (S - ((x - 1) * x) / 2)
From this, derive a formula to find x directly if it exists. Solving algebraically can help us identify the pivot integer without iteration.
Time Complexity: O(n).
Space Complexity: O(1).
1#include <cmath>
using namespace std;
int findPivot(int n) {
int total_sum = n * (n + 1) / 2;
for (int x = 1; x <= n; ++x) {
if (2 * x * x == total_sum + x * (x - 1)) return x;
}
return -1;
}
int main() {
int n = 8;
cout << findPivot(n) << endl;
return 0;
}
In C++, this method efficiently checks each number without recalculating the partial sums, simplifying the approach.