I'm trying to solve this problem at CodeForces:
There is an array
aof the size1e9filled with natural numbers with alternating sign:
- a[1] = -1
- a[2] = 2
- a[3] = -3
- a[4] = 4
- a[5] = -5
- and so on...
There are
qqueries (1 ≤ q ≤ 1000) each in the form of two numbers,landr(1 ≤ l ≤ r ≤ 1e9). The answer to a query is the sum of all the elements of the arrayaat positions fromltorinclusive.
Here's my code:
#include <stdio.h>
int solve(int l, int r)
{
long int res;
if ((l == r) && (l % 2 == 0)) {
res = l;
return res;
} else if ((l == r) && (l % 2 != 0)) {
res = l*(-1);
return res;
}
long int sum, esum, osum, min = l/2, max = r/2;
sum = (r*(r+1))/2 - ((l-1)*l)/2;
if (l % 2 == 0) {
min--;
}
esum = (max*(max+1)) - (min*(min+1));
osum = (sum-esum)*(-1);
res = esum + osum;
return res;
}
int main()
{
long int t, l, r;
scanf("%ld", &t);
while (t--) {
scanf("%ld %ld", &l, &r);
long res = solve(l, r);
printf("%ld\n", res);
}
return 0;
}
This code doesn't give an applicable result for a very large value. But it's OK for normal values. What could be the error?
Input
6
617758920 825919887
775957146 950878973
404173573 553845184
25837072 795166931
756434592 838258528
590139756 977664562
My Output
-104080484
2060022734
74835806
1762818718
797346560
783902159
Correct Answer
-104080484
-87460914
74835806
-384664930
797346560
783902159
Are you sure you need those squares...?
Each pair of consecutive odd- and even-indexed term gives a partial sum of 1. So all you need is a number of such pairs fitting within the given interval plus possibly a[l] if l is even and a[r] if r is odd.
Solution:
long solve(long l, long r)
{
long res = r/2 - l/2;
if (l % 2 == 0)
res += l;
if (r % 2 != 0)
res -= r;
return res;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With