Given a number N. The task is to find the sum of the below series up to nth term.
1- 2 + 3 – 4 + 5 – 6 +….
Examples:
Input : N = 8 Output : -4 Input : N = 10001 Output : 5001
Approach: If we observe carefully, we can see that the sum of the above series follows a pattern of alternating positive and negative integers starting from 1 to N as shown below:
N = 1, 2, 3, 4, 5, 6, 7 ...... Sum = 1, -1, 2, -2, 3, -3, 4 ......
Hence, from the above pattern, we can conclude that:
- when n is odd => sum = (n+1)/2
- when n is even => sum = (-1)*n/2
Below is the implementation of the above approach:
C++
// C++ program to find the sum of // series 1 - 2 + 3 - 4 +...... #include <iostream> using namespace std;
// Function to calculate sum int solve_sum( int n)
{ // when n is odd
if (n % 2 == 1)
return (n + 1) / 2;
// when n is not odd
return -n / 2;
} // Driver code int main()
{ int n = 8;
cout << solve_sum(n);
return 0;
} |
Java
// Java program to find sum of // first n terms of the given series import java.util.*;
class GFG
{ static int calculateSum( int n)
{ // when n is odd
if (n % 2 == 1 )
return (n + 1 ) / 2 ;
// when n is not odd
return -n / 2 ;
} // Driver code public static void main(String ar[])
{ // no. of terms to find the sum int n = 8 ;
System.out.println(calculateSum(n)); } } |
Python 3
# Python program to find the sum of # series 1 - 2 + 3 - 4 +...... # Function to calculate sum def solve_sum(n):
# when n is odd
if (n % 2 = = 1 ):
return (n + 1 ) / 2
# when n is not odd
return - n / 2
# Driver code n = 8
print ( int (solve_sum(n)))
|
C#
// C# program to find sum of // first n terms of the given series using System;
class GFG
{ static int calculateSum( int n)
{ // when n is odd
if (n % 2 == 1)
return (n + 1) / 2;
// when n is not odd
return -n / 2;
} // Driver code public static void Main()
{ // no. of terms to find the sum
int n = 8;
Console.WriteLine(calculateSum(n));
} } // This code is contributed // by inder_verma |
PHP
<?php // PHP program to find the sum of // series 1 - 2 + 3 - 4 +...... // Function to calculate sum function solve_sum( $n )
{ // when n is odd
if ( $n % 2 == 1)
return ( $n + 1) / 2;
// when n is not odd
return - $n / 2;
} // Driver code $n = 8;
echo solve_sum( $n );
// This code is contributed // by inder_verma ?> |
Javascript
<script> // javascript program to find sum of // first n terms of the given series function calculateSum(n)
{ // when n is odd
if (n % 2 == 1)
return (n + 1) / 2;
// when n is not odd
return -n / 2;
} // Driver code // no. of terms to find the sum var n = 8;
document.write(calculateSum(n)); // This code contributed by shikhasingrajput </script> |
Output:
-4
Time Complexity: O(1)
Auxiliary Space: O(1) , since no extra space has been taken.