You also have to take n as long long int cuz when you multiply two integers and if they overflow the result would be wrong. Consider multiplying 10^6 * 10^6, if you have stored 10^6 in int than the result would overflow. It doesn’t matter if you have declared the storing variable as ull.
total = n*(n-1)/2 is where i think an overflow is possible because the intermediate variable will be stored in integer. A get around for that is total = n;total =(total*(n-1))/2;
Other than overflow error, you got WA because you use
int total = n*((n+1)/2);
for n=4 , total=8
but it should be 10.
the formula should be int total = n*(n+1)/2; because associativity is from left to right and one out of n and n+1 will definitely be even.
so that n*(n+1) will be even…
That’s why your code will give wrong answer for n=even
there is a problem in your c++ code … your are taking n to be int and when you compute n*(n+1)/2 it tries to fit the answer in int …which overflows… so try taking long long int for int and you will get ac …also you need to change the statement n*((n+1)/2) to (n*(n+1))/2… this will get you a ac
with every addition of number arr[i] just subtract i+1 from the total sum and check weather the sum finally comes to be zero or not if zero then print yes else print no.
Code
long long int sum=0;
for(i=0;i<n;i++)
{
sum+=arr[i];
sum-=(i+1);
}