Author: Nishchith Shetty
Tester: Karan Sheth
Editorialist: Chirag Shetty
Given an integer n you have to print result adding all even nos till n and subtracting all odd nos tll n.
Since n is very large adding even nos one by one and subtracting odd nos one by one will give you TLE.
There are 2 simple cases.
- If n is even (say 10) then answer is n/2 (i.e 5)
If n is even then we can consider first n/2 odd numbers and
and first n/2 even numbers excluding 0 as 0 won’t add up to the sum.
For eg if n=10,
Odd nos - 1 3 5 7 9
Even nos - 2 4 6 8 10 (excluding 0)
Let k = n/2 (i.e 5)
Using sum of Arithmetic Progression Formula :
S = (k/2)*(2a+(k-1)*d)
Sum of even numbers (a=2,d=2)
S1 = (k/2)(4+(k-1)2)
S1 = (k/2)(2k+2)
S1 = kk+k
Sum of odd numbers (a=1,d=2)
S2 = (k/2)(2+(k-1)2)
S2 = (k/2)(2k)
S2 = kk
S1-S2 = k = n/2
- If n is odd (say 9) then answer is -(n+1)/2 (i.e -5)
If we take n+1 then that is even and we just need to subtract the last even number i.e n+1 from above formula.
i.e (n+1)/2-(n+1) = -(n+1)/2
AUTHOR’S AND TESTER’S SOLUTIONS:
Author’s solution can be found here.
Tester’s solution can be found here.