Calculating Function
Time | 31ms |
---|---|
Memory | 12kB |
Length | 160 |
For a positive integer n let's define a function f:
f(n) = - 1 + 2 - 3 + .. + ( - 1)nn
Your task is to calculate f(n) for a given integer n.
Input
The single line contains the positive integer n (1 ≤ n ≤ 1015).
Output
Print f(n) in a single line.
Examples
Input
4
Output
2
Input
5
Output
-3
Note
f(4) = - 1 + 2 - 3 + 4 = 2
f(5) = - 1 + 2 - 3 + 4 - 5 = - 3
问题链接:https://vjudge.net/contest/279613#problem/A
问题解释:1,2,3,,,n求和,奇数为负,偶数为正。输入n,输出求和结果。
解决方案:
如果定义一个函数,模拟来求和的话,可能会出现超时;
观察发现,如果有偶数个数求和,前后一对相加为1,故求和结果为n/2;
如果有奇数个数求和,先算前面n-1个数的和,即为int(n/2),再加上第n个数(-n),故求和结果为n/2-n。
AC代码:
#include <iostream>
using namespace std;
int main()
{
long long int n,i,fun=0;
cin >> n;
if (n % 2 == 0)fun = n / 2;
else fun = n / 2 - n;
cout << fun;
}