Suma de los elementos del índice L a R en una array cuando arr[i] = i * (-1)^i

Dados dos enteros  L   R   una array arr[], cada elemento del cual en el índice  i   se calcula como arr[i] = i * (-1) i . La tarea es encontrar la suma de estos elementos de la array dentro del rango del índice  [L, R]   .

Ejemplos: 

Entrada : L = 1, R = 5 
Salida: -3 
Suma = (-1) + 2 + (-3) + 4 + (-5) = -3

Entrada : L = 5, R = 100000000 
Salida: 49999998 

Enfoque ingenuo: de acuerdo con la definición de elementos de array, cada elemento impar de la array es negativo y el elemento par es positivo. Entonces, para encontrar la suma, ejecute un ciclo for desde (L a R) y mantenga la suma de todos los números impares (negativos) e pares (positivos). Finalmente, devuelve la suma.

Enfoque eficiente: se puede notar que la suma de todos los elementos impares de esta serie siempre será igual a (totalOdd) 2 donde totalOdd = número total de elementos impares y la suma de los números pares será totalEven * (totalEven + 1) . Ahora, todo lo que tenemos que hacer es encontrar la suma de todos los elementos impares hasta L y hasta R. Almacene la diferencia de ambos para obtener la suma de todos los elementos impares entre L y R. Haga lo mismo para los números pares y finalmente Devuelve la diferencia de sumas pares e impares.

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

C++

// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
 
// function to return the odd sum
long int Odd_Sum(int n)
{
 
    // total odd elements upto n
    long int total = (n + 1) / 2;
 
    // sum of odd elements upto n
    long int odd = total * total;
 
    return odd;
}
 
// function to return the even sum
long int Even_Sum(int n)
{
 
    // total even elements upto n
    long int total = (n) / 2;
 
    // sum of even elements upto n
    long int even = total * (total + 1);
 
    return even;
}
 
// Function to find sum from L to R.
int sumLtoR(int L, int R)
{
 
    long int odd_sum, even_sum;
 
    odd_sum = Odd_Sum(R) - Odd_Sum(L - 1);
 
    even_sum = Even_Sum(R) - Even_Sum(L - 1);
 
    // return final sum from L to R
    return even_sum - odd_sum;
}
 
// Driver Program
int main()
{
 
    int L = 1, R = 5;
 
    // function call to print answer
    cout << sumLtoR(L, R);
 
    return 0;
}

Java

// Java implementation of above approach
 
import java.io.*;
 
class GFG {
     
 
 
// function to return the odd sum
static long  Odd_Sum(int n)
{
 
    // total odd elements upto n
    long  total = (n + 1) / 2;
 
    // sum of odd elements upto n
    long  odd = total * total;
 
    return odd;
}
 
// function to return the even sum
static long  Even_Sum(int n)
{
 
    // total even elements upto n
    long  total = (n) / 2;
 
    // sum of even elements upto n
    long  even = total * (total + 1);
 
    return even;
}
 
// Function to find sum from L to R.
static long sumLtoR(int L, int R)
{
 
    long  odd_sum, even_sum;
 
    odd_sum = Odd_Sum(R) - Odd_Sum(L - 1);
 
    even_sum = Even_Sum(R) - Even_Sum(L - 1);
 
    // return final sum from L to R
    return even_sum - odd_sum;
}
 
// Driver Program
 
    public static void main (String[] args) {
        int L = 1, R = 5;
 
    // function call to print answer
    System.out.println( sumLtoR(L, R));
    }
}
// This code is contributed by shs..

Python3

# Python3 implementation of above approach
 
# function to return the odd sum
def Odd_Sum(n):
 
    # total odd elements upto n
    total =(n+1)//2
 
    # sum of odd elements upto n
    odd = total*total
    return odd
 
# function to return the even sum
def Even_Sum(n):
 
    # total even elements upto n
    total = n//2
 
    # sum of even elements upto n
    even = total*(total+1)
    return even
 
def sumLtoR(L,R):
    odd_sum = Odd_Sum(R)-Odd_Sum(L-1)
    even_sum = Even_Sum(R)- Even_Sum(L-1)
 
    # return final sum from L to R
    return even_sum-odd_sum
 
 
# Driver code
L =1; R = 5
print(sumLtoR(L,R))
 
# This code is contributed by Shrikant13

C#

// C# implementation of above approach
class GFG
{
     
// function to return the odd sum
static long Odd_Sum(int n)
{
 
    // total odd elements upto n
    long total = (n + 1) / 2;
 
    // sum of odd elements upto n
    long odd = total * total;
 
    return odd;
}
 
// function to return the even sum
static long Even_Sum(int n)
{
 
    // total even elements upto n
    long total = (n) / 2;
 
    // sum of even elements upto n
    long even = total * (total + 1);
 
    return even;
}
 
// Function to find sum from L to R.
static long sumLtoR(int L, int R)
{
    long odd_sum, even_sum;
 
    odd_sum = Odd_Sum(R) - Odd_Sum(L - 1);
 
    even_sum = Even_Sum(R) - Even_Sum(L - 1);
 
    // return final sum from L to R
    return even_sum - odd_sum;
}
 
// Driver Code
public static void Main ()
{
    int L = 1, R = 5;
 
    // function call to print answer
    System.Console.WriteLine(sumLtoR(L, R));
}
}
 
// This code is contributed by mits

PHP

<?php
// PHP implementation of above approach
 
// function to return the odd sum
function Odd_Sum($n)
{
 
    // for total odd elements upto n
    // divide by 2
    $total = ($n + 1) >> 1;
 
    // sum of odd elements upto n
    $odd = $total * $total;
 
    return $odd;
}
 
// function to return the even sum
function Even_Sum($n)
{
 
    // for total even elements upto n
    // divide by 2
    $total = $n >> 1;
     
    // sum of even elements upto n
    $even = $total * ($total + 1);
 
    return $even;
}
 
// Function to find sum from L to R.
function sumLtoR($L, $R)
{
    $odd_sum = Odd_Sum($R) -
               Odd_Sum($L - 1);
 
    $even_sum = Even_Sum($R) -
                Even_Sum($L - 1);
 
     
    // print final sum from L to R
    return $even_sum - $odd_sum ;
}
 
// Driver Code
$L = 1 ;
$R = 5;
 
// function call to print answer
echo sumLtoR($L, $R);
 
// This code is contributed by ANKITRAI1
?>

Javascript

<script>
 
// Javascript implementation of above approach
 
// Function to return the odd sum
function Odd_Sum(n)
{
     
    // Total odd elements upto n
    var total = parseInt((n + 1) / 2);
 
    // Sum of odd elements upto n
    var odd = total * total;
 
    return odd;
}
 
// Function to return the even sum
function Even_Sum(n)
{
     
    // Total even elements upto n
    var total = parseInt((n) / 2);
 
    // Sum of even elements upto n
    var even = total * (total + 1);
 
    return even;
}
 
// Function to find sum from L to R.
function sumLtoR(L, R)
{
    var odd_sum, even_sum;
 
    odd_sum = Odd_Sum(R) - Odd_Sum(L - 1);
    even_sum = Even_Sum(R) - Even_Sum(L - 1);
 
    // Return final sum from L to R
    return even_sum - odd_sum;
}
 
// Driver code
var L = 1, R = 5;
 
// Function call to print answer
document.write(sumLtoR(L, R));
 
// This code is contributed by SoumikMondal
 
</script>
Producción: 

-3

 

Complejidad de tiempo: O(1)

Espacio Auxiliar: O(1)

Publicación traducida automáticamente

Artículo escrito por Sanjit_Prasad 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 *