Suma de series formadas por diferencia entre producto y suma de N números naturales

Dado un número natural N , la tarea es encontrar la suma de la serie hasta el N-ésimo término , donde el i- ésimo término denota la diferencia entre el producto de los primeros i números naturales y la suma de los primeros i números naturales , es decir,

{ 1 – 1 } + { (1 * 2) – (2 + 1) } + { (1 * 2 * 3) – (3 + 2 + 1) } + { (1 * 2 * 3 * 4) – ( 4 + 3 + 2 + 1) } + ……… 

Ejemplos:  

Entrada:
Salida: -1 
Explicación: { 1 – 1 } + { (1 * 2) – (2 + 1) } = { 0 } + { -1 } = -1

Entrada:
Salida: 13 
Explicación: 
{ 0 } + { (1 * 2) – (2 + 1) } + { (1 * 2 * 3) – (3 + 2 + 1) } + { (1 * 2 * 3 * 4) – (4 + 3 + 2 + 1) } 
= { 0 } + { -1 } + { 0 } + { 14 } 
= 0 – 1 + 0 + 14 
= 13

Enfoque iterativo: 
siga los pasos a continuación para resolver el problema:  

  • Inicializar tres variables: 
    • currProd: Almacena el producto de todos los números naturales hasta el término actual.
    • currSum: Almacena la suma de todos los números naturales hasta el término actual.
    • suma: almacena la suma de la serie hasta el término actual
  • Inicialice currSum = 1, currSum = 1 y sum = 0 (Since, 1 – 1 = 0) para almacenar sus respectivos valores para el primer término.
  • Iterar sobre el rango [2, N] y actualizar lo siguiente para cada i- ésima iteración: 
    • sumaActual = sumaActual + i
    • currProd = currProd * i
    • suma = currProd – currSum
  • Devuelve el valor final de sum .

A continuación se muestra la implementación del enfoque anterior:  

C++

// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to
// calculate the
// sum upto Nth term
int seriesSum(int n)
{
    // Stores the sum
    // of the series
    int sum = 0;
 
    // Stores the
    // product of
    // natural numbers
    // upto the
    // current term
    int currProd = 1;
 
    // Stores the sum
    // of natural numbers
    // upto the
    // upto current term
    int currSum = 1;
 
    // Generate the remaining
    // terms and calculate sum
    for (int i = 2; i <= n; i++) {
        currProd *= i;
        currSum += i;
 
        // Update the sum
        sum += currProd
               - currSum;
    }
 
    // Return the sum
    return sum;
}
 
// Driver Program
int main()
{
    int N = 5;
    cout << seriesSum(N) << " ";
}

Java

// Java program to implement the
// above approach
import java.lang.*;
 
class GFG{
 
// Function to calculate the
// sum upto Nth term
static int seriesSum(int n)
{
     
    // Stores the sum
    // of the series
    int sum = 0;
 
    // Stores the product of
    // natural numbers upto
    // the current term
    int currProd = 1;
 
    // Stores the sum of natural
    // numbers upto the upto
    // current term
    int currSum = 1;
 
    // Generate the remaining
    // terms and calculate sum
    for(int i = 2; i <= n; i++)
    {
       currProd *= i;
       currSum += i;
        
       // Update the sum
       sum += currProd - currSum;
    }
 
    // Return the sum
    return sum;
}
 
// Driver code
public static void main(String[] args)
{
    int N = 5;
     
    System.out.print(seriesSum(N));
}
}
 
// This code is contributed by rock_cool

Python3

# Python3 program to implement
# the above approach
 
# Function to calculate the
# sum upto Nth term
def seriesSum(n):
 
    # Stores the sum
    # of the series
    sum1 = 0;
 
    # Stores the product of
    # natural numbers upto the
    # current term
    currProd = 1;
 
    # Stores the sum of natural numbers
    # upto the upto current term
    currSum = 1;
 
    # Generate the remaining
    # terms and calculate sum
    for i in range(2, n + 1):
        currProd *= i;
        currSum += i;
 
        # Update the sum
        sum1 += currProd - currSum;
     
    # Return the sum
    return sum1;
 
# Driver Code
N = 5;
print(seriesSum(N), end = " ");
 
# This code is contributed by Code_Mech

C#

// C# program to implement the
// above approach
using System;
class GFG{
 
// Function to calculate the
// sum upto Nth term
static int seriesSum(int n)
{
     
    // Stores the sum
    // of the series
    int sum = 0;
 
    // Stores the product of
    // natural numbers upto
    // the current term
    int currProd = 1;
 
    // Stores the sum of natural
    // numbers upto the upto
    // current term
    int currSum = 1;
 
    // Generate the remaining
    // terms and calculate sum
    for(int i = 2; i <= n; i++)
    {
        currProd *= i;
        currSum += i;
             
        // Update the sum
        sum += currProd - currSum;
    }
 
    // Return the sum
    return sum;
}
 
// Driver code
public static void Main()
{
    int N = 5;
     
    Console.Write(seriesSum(N));
}
}
 
// This code is contributed by Code_Mech

Javascript

<script>
 
    // Javascript program to implement
    // the above approach
     
    // Function to
    // calculate the
    // sum upto Nth term
    function seriesSum(n)
    {
        // Stores the sum
        // of the series
        let sum = 0;
 
        // Stores the
        // product of
        // natural numbers
        // upto the
        // current term
        let currProd = 1;
 
        // Stores the sum
        // of natural numbers
        // upto the
        // upto current term
        let currSum = 1;
 
        // Generate the remaining
        // terms and calculate sum
        for (let i = 2; i <= n; i++) {
            currProd *= i;
            currSum += i;
 
            // Update the sum
            sum += currProd
                   - currSum;
        }
 
        // Return the sum
        return sum;
    }
 
    let N = 5;
    document.write(seriesSum(N) + " ");
     
</script>
Producción: 

118

 

Complejidad temporal: O(N)  
Espacio auxiliar: O(1)

Enfoque recursivo:  

  • Calcule recursivamente la suma llamando a la función que actualiza K (denota el término actual).
  • Actualizar prevSum precalculado agregando multi * K – suma + K
  • Calcule recursivamente todos los valores de K actualizando prevSum, multi y add en cada iteración.
  • Finalmente, devuelva el valor de prevSum.

A continuación se muestra la implementación del enfoque anterior:  

C++

// C++ program to calculate the
// sum upto the Nth term of the
// given series
 
#include <bits/stdc++.h>
using namespace std;
 
// Recursive Function to calculate the
// sum upto Nth term
int seriesSumUtil(int k, int n,
                  int prevSum,
                  int multi, int add)
{
    // If N-th term is calculated
    if (k == n + 1) {
        return prevSum;
    }
 
    // Update multi to store
    // product upto K
    multi = multi * k;
 
    // Update add to store
    // sum upto K
    add = add + k;
 
    // Update prevSum to store sum
    // upto K
    prevSum = prevSum + multi - add;
 
    // Proceed to next K
    return seriesSumUtil(k + 1, n, prevSum,
                         multi, add);
}
 
// Function to calculate
// and return the
// Sum upto Nth term
int seriesSum(int n)
{
    if (n == 1)
        return 0;
    int prevSum = 0;
    int multi = 1;
    int add = 1;
 
    // Recursive Function
    return seriesSumUtil(2, n, prevSum,
                         multi, add);
}
 
// Driver Program
int main()
{
    int N = 5;
    cout << seriesSum(N) << " ";
}

Java

// Java program to calculate the
// sum upto the Nth term of the
// given series
class GFG{
     
// Recursive Function to calculate the
// sum upto Nth term
static int seriesSumUtil(int k, int n,
                         int prevSum,
                         int multi, int add)
{
     
    // If N-th term is calculated
    if (k == n + 1)
    {
        return prevSum;
    }
 
    // Update multi to store
    // product upto K
    multi = multi * k;
 
    // Update add to store
    // sum upto K
    add = add + k;
 
    // Update prevSum to store sum
    // upto K
    prevSum = prevSum + multi - add;
 
    // Proceed to next K
    return seriesSumUtil(k + 1, n, prevSum,
                         multi, add);
}
 
// Function to calculate and
// return the Sum upto Nth term
static int seriesSum(int n)
{
    if (n == 1)
        return 0;
         
    int prevSum = 0;
    int multi = 1;
    int add = 1;
 
    // Recursive Function
    return seriesSumUtil(2, n, prevSum,
                         multi, add);
}
 
// Driver code
public static void main(String []args)
{
    int N = 5;
    System.out.println(seriesSum(N));
}
}
 
// This code is contributed by Ritik Bansal

Python3

# Python3 program to calculate the
# sum upto the Nth term of the
# given series
 
# Recursive Function to calculate the
# sum upto Nth term
def seriesSumUtil(k, n, prevSum, multi, add):
   
    # If N-th term is calculated
    if (k == n + 1):
        return prevSum;
 
    # Update multi to store
    # product upto K
    multi = multi * k;
 
    # Update add to store
    # sum upto K
    add = add + k;
 
    # Update prevSum to store sum
    # upto K
    prevSum = prevSum + multi - add;
 
    # Proceed to next K
    return seriesSumUtil(k + 1, n,
                         prevSum, multi, add);
 
# Function to calculate and
# return the Sum upto Nth term
def seriesSum(n):
    if (n == 1):
        return 0;
 
    prevSum = 0;
    multi = 1;
    add = 1;
 
    # Recursive Function
    return seriesSumUtil(2, n, prevSum,
                         multi, add);
 
# Driver code
if __name__ == '__main__':
    N = 5;
    print(seriesSum(N));
 
# This code is contributed by Princi Singh

C#

// C# program to calculate the
// sum upto the Nth term of the
// given series
using System;
class GFG{
     
// Recursive Function to calculate the
// sum upto Nth term
static int seriesSumUtil(int k, int n,
                         int prevSum,
                         int multi, int add)
{
     
    // If N-th term is calculated
    if (k == n + 1)
    {
        return prevSum;
    }
 
    // Update multi to store
    // product upto K
    multi = multi * k;
 
    // Update add to store
    // sum upto K
    add = add + k;
 
    // Update prevSum to store sum
    // upto K
    prevSum = prevSum + multi - add;
 
    // Proceed to next K
    return seriesSumUtil(k + 1, n, prevSum,
                         multi, add);
}
 
// Function to calculate and
// return the Sum upto Nth term
static int seriesSum(int n)
{
    if (n == 1)
        return 0;
         
    int prevSum = 0;
    int multi = 1;
    int add = 1;
 
    // Recursive Function
    return seriesSumUtil(2, n, prevSum,
                         multi, add);
}
 
// Driver code
public static void Main(String []args)
{
    int N = 5;
    Console.WriteLine(seriesSum(N));
}
}
 
// This code is contributed by Rohit_ranjan

Javascript

<script>
 
// Javascript program to calculate the
// sum upto the Nth term of the
// given series
 
// Recursive Function to calculate the
// sum upto Nth term
function seriesSumUtil(k, n, prevSum, multi, add)
{
     
    // If N-th term is calculated
    if (k == n + 1)
    {
        return prevSum;
    }
 
    // Update multi to store
    // product upto K
    multi = multi * k;
 
    // Update add to store
    // sum upto K
    add = add + k;
 
    // Update prevSum to store sum
    // upto K
    prevSum = prevSum + multi - add;
 
    // Proceed to next K
    return seriesSumUtil(k + 1, n, prevSum,
                         multi, add);
}
 
// Function to calculate and
// return the Sum upto Nth term
function seriesSum(n)
{
    if (n == 1)
        return 0;
 
    let prevSum = 0;
    let multi = 1;
    let add = 1;
 
    // Recursive Function
    return seriesSumUtil(2, n, prevSum,
                         multi, add);
}
 
// Driver code
let N = 5;
document.write(seriesSum(N));
 
// This code is contributed by rameshtravel07
 
</script>
Producción: 

118

 

Complejidad temporal: O(N)  
Espacio auxiliar: O(1)
 

Publicación traducida automáticamente

Artículo escrito por MohammadMudassir y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *