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!!!!!!
相關文章
- javascript 中function(){},new function(),new Function(),Function 摘錄JavaScriptFunction
- JavaScript FunctionJavaScriptFunction
- [Bash] functionFunction
- python FunctionPythonFunction
- Loss FunctionFunction
- java.util.function 中的 Function、Predicate、ConsumerJavaFunction
- Function型別Function型別
- DMSQL WITH FUNCTION子句SQLFunction
- JavaScript Function物件JavaScriptFunction物件
- Function pointers and callbacksFunction
- addEventListener("touchend", function ()_devFunction
- TypeError: stringWidth is not a functionErrorFunction
- flask 裝飾器 AssertionError: View function mapping is overwriting an existing endpoint functionFlaskErrorViewFunctionAPP
- JavaScript function 函式JavaScriptFunction函式
- (function($,window,document){.......})用法Function
- Function.prototype.callFunction
- Uncaught TypeError: i is not a functionErrorFunction
- python - function list generatorPythonFunction
- JavaScript中的 FunctionJavaScriptFunction
- C++ function pointersC++Function
- [Vue] Use render functionVueFunction
- jasmine.any(Function)ASMFunction
- drools中使用functionFunction
- bypass disable_functionFunction
- 深究Function.prototype.bindFunction
- new 了一個 FunctionFunction
- CSS transition-timing-functionCSSFunction
- Lambda Function, Callable, Optional in PythonFunctionPython
- std::function用法學習Function
- CF1098F Ж-functionFunction
- TypeError: loaderContext.getOptions is not a functionErrorContextFunction
- Important SAP APO Function Modules!ImportFunction
- class中的arrow functionFunction
- [Javascript] Why need arrow function?JavaScriptFunction
- G. D-FunctionFunction
- 關於 HANA CE FunctionFunction
- await is only valid in async functionAIFunction
- 【Azure Function App】Azure Function 從.Net6 升級到 .Net8 後 Function出現執行時版本錯誤FunctionAPP