Sigma of Equation Given a number N, find the value of the below equation for the given number.
Equation
N
∑ {(X + 1)^2 - (3X + 1) + X}
X = 1
Input Format
First line contains an integer n
Output Format
Single line output representing the value.
Example 1
Input
1
Output
1
Example 2
Input
2
Output
5
Explanation
{(1+1)² - (3x1+1) + (1)} + {(2+1)² - (3x2+1) +2} = 4 - 4 +1 + 9 -7 +2 = 5
Constraints
1 <= n <= 105
**I have two solution one is working and second is not working for some test cases like n=100000.
Solution 1(Working):**
import java.util.*;
import static java.lang.Math.ceil;
class Solution {
public long SigmaEquation(int n ) {
long ans=0;
for(int i=1; i<=n; i++){
ans = ans + (long)(Math.pow((i+1),2)-((3*i)+1)+i);
}
return ans;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Solution Obj = new Solution();
System.out.println(Obj.SigmaEquation(n));
}
}
Solution 2(error for some test cases like n= 100000 ):-
import java.util.*;
import static java.lang.Math.ceil;
class Solution {
public long SigmaEquation(int n ) {
long ans=0;
for(int i=1; i<=n; i++){
ans = ans + (((i+1)*(i+1))-((3*i)+1)+i);
}
return ans;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Solution Obj = new Solution();
System.out.println(Obj.SigmaEquation(n));
}
}
Getting this issue for solution 2 why?
and why the same issue solved in solution 1 program?
Wrong Answer
Time Limit : 171ms
Time Taken By Your Code : 152ms
Input
100000
Correct Output
333338333350000
Your Output
18104913692784