Formula: abs((1+2+....n)^2-(1^2+2^2+3^2+...n^2))
Example 1:
Input : n=10 Output: 2640
Approach:
Java
public class SumSquareDifference {
public static void main(String[] args) {
int num = 10;
int diff = sumOfSquareDiffe(num);
System.out.println(diff);
}
private static int sumOfSquareDiffe(int n) {
int sum1 = 0;
for (int i = 1; i <= n; i++)
sum1 += i * i;
int sum2 = n * (n + 1) / 2;
sum2 = sum2 * sum2;
return Math.abs(sum1 - sum2);
}
}
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n=10;
int sum1=0;
for(int i=1;i<=n;i++)
sum1+=i*i;
int sum2=n*(n+1)/2;
sum2=sum2*sum2;
cout<<abs(sum1-sum2)<<"\n";
return 0;
}
No comments:
Post a Comment