Find sum of the series 1-2+3-4+5-6+7…….
Last Updated :
17 Nov, 2022
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++
#include <iostream>
using namespace std;
int solve_sum( int n)
{
if (n % 2 == 1)
return (n + 1) / 2;
return -n / 2;
}
int main()
{
int n = 8;
cout << solve_sum(n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int calculateSum( int n)
{
if (n % 2 == 1 )
return (n + 1 ) / 2 ;
return -n / 2 ;
}
public static void main(String ar[])
{
int n = 8 ;
System.out.println(calculateSum(n));
}
}
|
Python 3
def solve_sum(n):
if (n % 2 = = 1 ):
return (n + 1 ) / 2
return - n / 2
n = 8
print ( int (solve_sum(n)))
|
C#
using System;
class GFG
{
static int calculateSum( int n)
{
if (n % 2 == 1)
return (n + 1) / 2;
return -n / 2;
}
public static void Main()
{
int n = 8;
Console.WriteLine(calculateSum(n));
}
}
|
PHP
<?php
function solve_sum( $n )
{
if ( $n % 2 == 1)
return ( $n + 1) / 2;
return - $n / 2;
}
$n = 8;
echo solve_sum( $n );
?>
|
Javascript
<script>
function calculateSum(n)
{
if (n % 2 == 1)
return (n + 1) / 2;
return -n / 2;
}
var n = 8;
document.write(calculateSum(n));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1) , since no extra space has been taken.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...