📌  相关文章
📜  求出系列1-2 + 3-4 + 5-6 + 7……的总和。

📅  最后修改于: 2021-05-04 23:36:19             🧑  作者: Mango

给定一个数N的任务是找到的下方串联了起来总和至N项。

例子

Input : N = 8
Output : -4

Input : N = 10001
Output : 5001

方法:如果仔细观察,我们可以看到上述系列的总和遵循从1到N的正整数和负整数交替排列的模式,如下所示:

N   = 1, 2, 3, 4, 5, 6, 7 ......
Sum = 1, -1, 2, -2, 3, -3, 4 ......

因此,从上述模式中,我们可以得出结论:

  • 当n为奇数=> sum =(n + 1)/ 2
  • 当n是偶数时=> sum =(-1)* n / 2

下面是上述方法的实现:

C++
// C++ program to find the sum of
// series 1 - 2 + 3 - 4 +......
 
#include 
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


Javascript


输出:
-4