Q. f(n) = - 1 + 2 - 3 + .. + ( - 1) n n . Given n, find out f(n)
Approach(1)- Bruteforce:
1. Calculation sum=n*(n+1)/2
2. loop[i=1,i=n : i+=2] odd+=i
3.ans=sum-2*odd
Code:
- #include <bits/stdc++.h>
- using namespace std;
- int main(){
- long long x;
- cin>>x;
- long long p=(x*(x+1))/2;
- long long bad=0;
- for(long long i=1;i<=x;i+=2)
- bad+=i;
- cout<<p-2*bad<<endl;
- }
Approach(2)-Greedy:
Basic:
s=1+2+3+4+....+n
Formula: sum=n*(n+1)/2= (n/2) + (n+1).2
here n/2 denotes the summation of all even numbers and (n+1)/2 denotes the summation of all odd numbers.
- 1.if n is even answer=n/2
n=6
-1+2-3+4-5+6 =(2+4+6)-(1+3+5)= 12-9=3
- if n is odd answer=(n-1)/(2-n)=-(n+1)/2
n=5
-1+2-3+4-5 =(2+4)-(1+3+5)=6-9=-3
We got -1 in the formula because of (-1)^n. here n is odd. that's why we'll
get -1 for one time always in the case of odd numbers.
Code:
- #include <bits/stdc++.h>
- using namespace std;
- int main(){
- long long x,y,n;
- cin>>n;
- if(n%2==0)cout<<n/2<<endl;
- else cout<<-(n+1)/2<<endl;
- }
Test-Case Observation:
Comments
Post a Comment