Dado un número N. La tarea es encontrar la suma de la siguiente serie hasta el término n .
1- 2 + 3 – 4 + 5 – 6 +….
Ejemplos :
Input : N = 8 Output : -4 Input : N = 10001 Output : 5001
Enfoque: Si observamos cuidadosamente, podemos ver que la suma de la serie anterior sigue un patrón de números enteros positivos y negativos alternos que comienzan de 1 a N, como se muestra a continuación:
N = 1, 2, 3, 4, 5, 6, 7 ...... Sum = 1, -1, 2, -2, 3, -3, 4 ......
Por lo tanto, del patrón anterior, podemos concluir que:
- cuando n es impar => suma = (n+1)/2
- cuando n es par => suma = (-1)*n/2
A continuación se muestra la implementación del enfoque anterior:
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>
Producción:
-4