Question - 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 ≤ 10^15).
Output - Print f(n) in a single line.
Link to question - https://codeforces.com/problemset/problem/486/A
My code -
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
long long t,sum=0;
cin >> t;
for(long long i=1;i<=t;i++){
if(i%2!=0){
sum = sum - i;
}else{
sum = sum + i;
}
}
cout << sum;
}
The code seems to produce the correct output, however the time limit is a problem. Time limit per test is 1 second. When the input is 1000000000000000 , it says time limit exceeded and fails the test case. How do I reduce the time taken for my code?
Aucun commentaire:
Enregistrer un commentaire