PRADIPSUM - Easy Math Editorial SPOJ - UCS - Latest Problem Solution - Unleash-Coding-Skills

## Sunday, 30 September 2018

This is Editorial for  PRADIPSUM - Easy Math in Spoj. The link to the problem is:

The is a Simple logic problem with some corner cases. We can know to discuss that corner.

The first one is a range of the problem is you directly use formula without considering the negative number it will lead to the wrong answer.

suppose n1 and n2 are the numbers for one test case in the input. For simplicity in our solution, we will consider that n1<n2 if they are not in that format we can swap values of n1 and n2 so that n1 will be less than n2 always.

Cases after making n1<n2 we need to check for making logic:

Case1 --->  n1<= 0 and n2 <= 0

Case2---> n1 >= 0 and n2 >= 0

Case3---> n1<= 0  and n2 >= 0

General formula for sum of first 'n' natural number: i.e 1+2+...+n

(n*(n+1))/2

By using this only we are going to design our formulas.

Case2 formula: ((n2*n2-n1*n1)+(n2-n1))/2+n1;

Case2 formula:

1. n1=(n1*(n1+1))/2;
2. n2=(n2*(n2+1))/2;
3. n1=-n1;
4. ans=n1+n2;

The CPP solution for the problem PRADIPSUM - Easy Math  is:

#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
long long int n1,n2,ans,flag;

while(cin>>n1)
{
cin>>n2;
flag=0;
if(n1==n2)
{
cout<<n1<<endl;
continue;
}
if(n1>n2)
{
swap(n1,n2);
}
if((n1<=0&&n2<=0))
{
flag=1;
n1=abs(n1);
n2=abs(n2);
ans = ((n2*n2-n1*n1)+(n2-n1))/2;
ans-=n2;
cout<<ans<<endl;
}
else if((n1>=0&&n2>=0))
{
flag=0;
n1=abs(n1);
n2=abs(n2);
ans = ((n2*n2-n1*n1)+(n2-n1))/2;
ans+=n1;
cout<<ans<<endl;
}
else
{
n1=abs(n1);
n2=abs(n2);
n1=(n1*(n1+1))/2;
n2=(n2*(n2+1))/2;
n1=-n1;
ans=n1+n2;
cout<<ans<<endl;
}
}
return 0;
}

Tags: