Encuentre la suma de todos los elementos de la array que son equidistantes de dos potencias de 2 consecutivas

Dada una array arr[] que consta de N enteros, la tarea es encontrar la suma de los elementos de la array que son equidistantes de las dos potencias de 2 consecutivas .

Ejemplos:

Entrada: arr[] = {10, 24, 17, 3, 8}
Salida: 27
Explicación:
Los siguientes elementos de la array son equidistantes de dos potencias de 2 consecutivas:

  1. arr[1] (= 24) está igualmente separado de 2 4 y 2 5 .
  2. arr[3] (= 3) está igualmente separado de 2 1 y 2 2 .

Por lo tanto, la suma de 24 y 3 es 27.

Entrada: arr[] = {17, 5, 6, 35}
Salida: 6

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

  • Inicialice una variable, digamos res , que almacene la suma de los elementos de la array .
  • Recorra la array dada arr[] y realice los siguientes pasos:
    • Encuentra el valor de log 2 (arr[i]) y guárdalo en una variable, digamos power .
    • Encuentre el valor de 2 (potencia) y 2 (potencia + 1) y guárdelos en variables, digamos LesserValue y LargerValue , respectivamente.
    • Si el valor de (arr[i] – LesserValue) es igual a (LargerValue – arr[i]) , entonces incremente el valor de res por arr[i] .
  • Después de completar los pasos anteriores, imprima el valor de res como la suma resultante.

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

C++

// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to print the sum of array
// elements that are equidistant from
// two consecutive powers of 2
int FindSum(int arr[], int N)
{
    // Stores the resultant sum of the
    // array elements
    int res = 0;
 
    // Traverse the array arr[]
    for (int i = 0; i < N; i++) {
 
        // Stores the power of 2 of the
        // number arr[i]
        int power = log2(arr[i]);
 
        // Stores the number which is
        // power of 2 and lesser than
        // or equal to arr[i]
        int LesserValue = pow(2, power);
 
        // Stores the number which is
        // power of 2 and greater than
        // or equal to arr[i]
        int LargerValue = pow(2, power + 1);
 
        // If arr[i] - LesserValue is the
        // same as LargerValue-arr[i]
        if ((arr[i] - LesserValue)
            == (LargerValue - arr[i])) {
 
            // Increment res by arr[i]
            res += arr[i];
        }
    }
 
    // Return the resultant sum res
    return res;
}
 
// Driver Code
int main()
{
    int arr[] = { 10, 24, 17, 3, 8 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << FindSum(arr, N);
 
    return 0;
}

Java

// Java program for the above approach
 
class GFG {
 
    // Function to print the sum of array
    // elements that are equidistant from
    // two consecutive powers of 2
    static int FindSum(int[] arr, int N)
    {
        // Stores the resultant sum of the
        // array elements
        int res = 0;
 
        // Traverse the array arr[]
        for (int i = 0; i < N; i++) {
 
            // Stores the power of 2 of the
            // number arr[i]
            int power
                = (int)(Math.log(arr[i]) / Math.log(2));
 
            // Stores the number which is
            // power of 2 and lesser than
            // or equal to arr[i]
            int LesserValue = (int)Math.pow(2, power);
 
            // Stores the number which is
            // power of 2 and greater than
            // or equal to arr[i]
            int LargerValue = (int)Math.pow(2, power + 1);
 
            // If arr[i] - LesserValue is the
            // same as LargerValue-arr[i]
            if ((arr[i] - LesserValue)
                == (LargerValue - arr[i])) {
 
                // Increment res by arr[i]
                res += arr[i];
            }
        }
 
        // Return the resultant sum res
        return res;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[] arr = { 10, 24, 17, 3, 8 };
        int N = arr.length;
        System.out.println(FindSum(arr, N));
    }
}
 
// This code is contributed by ukasp.

Python3

# Python3 program for the above approach
from math import log2
 
# Function to print sum of array
# elements that are equidistant from
# two consecutive powers of 2
def FindSum(arr, N):
     
    # Stores the resultant sum of the
    # array elements
    res = 0
 
    # Traverse the array arr[]
    for i in range(N):
         
        # Stores the power of 2 of the
        # number arr[i]
        power = int(log2(arr[i]))
 
        # Stores the number which is
        # power of 2 and lesser than
        # or equal to arr[i]
        LesserValue = pow(2, power)
 
        # Stores the number which is
        # power of 2 and greater than
        # or equal to arr[i]
        LargerValue = pow(2, power + 1)
 
        # If arr[i] - LesserValue is the
        # same as LargerValue-arr[i]
        if ((arr[i] - LesserValue) ==
            (LargerValue - arr[i])):
             
            # Increment res by arr[i]
            res += arr[i]
 
    # Return the resultant sum res
    return res
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 10, 24, 17, 3, 8 ]
    N = len(arr)
     
    print (FindSum(arr, N))
 
# This code is contributed by mohit kumar 29

C#

// C# program for the above approach
using System;
  
class GFG{
  
// Function to print the sum of array
// elements that are equidistant from
// two consecutive powers of 2
static int FindSum(int[] arr, int N)
{
    // Stores the resultant sum of the
    // array elements
    int res = 0;
  
    // Traverse the array arr[]
    for (int i = 0; i < N; i++) {
  
        // Stores the power of 2 of the
        // number arr[i]
        int power = (int)(Math.Log(arr[i]) / Math.Log(2));
  
        // Stores the number which is
        // power of 2 and lesser than
        // or equal to arr[i]
        int LesserValue = (int)Math.Pow(2, power);
  
        // Stores the number which is
        // power of 2 and greater than
        // or equal to arr[i]
        int LargerValue = (int)Math.Pow(2, power + 1);
  
        // If arr[i] - LesserValue is the
        // same as LargerValue-arr[i]
        if ((arr[i] - LesserValue)
            == (LargerValue - arr[i])) {
  
            // Increment res by arr[i]
            res += arr[i];
        }
    }
  
    // Return the resultant sum res
    return res;
}
 
  
// Driver Code
public static void Main()
{
   int[] arr= { 10, 24, 17, 3, 8 };
    int N = arr.Length;
     Console.WriteLine(FindSum(arr, N));
 
}
}
 
// This code is contributed by code_hunt.

Javascript

<script>
 
// Javascript program for the above approach
 
// Function to print the sum of array
// elements that are equidistant from
// two consecutive powers of 2
function FindSum(arr, N)
{
     
    // Stores the resultant sum of
    // the array elements
    let res = 0;
 
    // Traverse the array arr[]
    for(let i = 0; i < N; i++)
    {
         
        // Stores the power of 2 of the
        // number arr[i]
        let power = Math.floor(
            Math.log2(arr[i]));
 
        // Stores the number which is
        // power of 2 and lesser than
        // or equal to arr[i]
        let LesserValue = Math.pow(2, power);
 
        // Stores the number which is
        // power of 2 and greater than
        // or equal to arr[i]
        let LargerValue = Math.pow(2, power + 1);
 
        // If arr[i] - LesserValue is the
        // same as LargerValue-arr[i]
        if ((arr[i] - LesserValue) ==
            (LargerValue - arr[i]))
        {
             
            // Increment res by arr[i]
            res += arr[i];
        }
    }
     
    // Return the resultant sum res
    return res;
}
 
// Driver Code
let arr = [ 10, 24, 17, 3, 8 ];
let N = arr.length;
 
document.write(FindSum(arr, N));
 
// This code is contributed by sanjoy_62
 
</script>
Producción: 

27

 

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

Publicación traducida automáticamente

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