Calculating Function
Practice this coding question on Coding Gurukul.
Problem statement
A finance puzzle models an alternating sequence of debits and credits. Entry 1 removes one unit, entry 2 adds two units, entry 3 removes three units, and so on. An analyst wants the net balance after entry n. The ledger may contain far too many entries to write them all down, so the calculation must work directly from the final entry number. Your task Compute -1 + 2 - 3 + 4 - ... through n, subtracting odd integers and adding even integers. Return the exact signed total. Each integer from 1 through n appears exactly once, and the sign is determined by that integer’s parity. Important details Use an integer type large enough for the stated bound. A loop with one iteration per entry is not appropriate for the largest inputs. An odd final entry leaves a final debit after the complete pairs. Worked example For n = 5, the balance is -1 + 2 - 3 + 4 - 5 = -3, so the program prints -3.
Input format
One integer n.
Output format
Print the signed value of the alternating sum.
Constraints
1 <= n <= 1000000000000000.
Sample input
5
Sample output
-3
Sign in to run or submit a solution in C++, Java or Python.