A.Calculating Function

A. Calculating Function
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
For a positive integer n let’s define a function f:

f(n) =  - 1 + 2 - 3 + … + [( - 1)^n]*n

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
inputCopy
4
outputCopy
2
inputCopy
5
outputCopy
-3
Note
f(4) =  - 1 + 2 - 3 + 4 = 2

f(5) =  - 1 + 2 - 3 + 4 - 5 = -3

本题目很简单,只不过需要注意的是n的取值范围,n 的范围很大,本题需要开long long。
用循环做的话,在n的范围很小的时候可以使用,但是本题的n的范围很大,所以我们要么是找规律,要么缩减问题规模,很明显是找规律,先去找偶数的规律,永远是所给n值的一半,可先假设,再进行数学归纳法,奇数可根据偶数的规律求解。
n是偶数,f=n/2,n是奇数,f=(n-1)/2-n
在n的范围很小的时候的代码段:

#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
int sum=0;
int flag=-1;
cin>>n;
for(int i=1;i<=n;i++)
{
sum+=iflag;
flag=flag
(-1);
}
cout<<sum<<endl;
// system(“pause”);
}
本题的代码段:
#include<bits/stdc++.h>
using namespace std;
int main()
{
long long n;
scanf("%lld",&n);
if(n&1)
printf("%lld\n",(n-1)/2-n);
else
printf("%lld\n",n/2);
}
注意:数要开long long!!!!!!

猜你喜欢

转载自blog.csdn.net/weixin_46006714/article/details/109688152