Encuentre la diferencia absoluta entre las potencias más cercanas de dos enteros dados para cada elemento de array

Dada una array arr[] que consiste en N enteros positivos y dos enteros positivos A y B , la tarea es reemplazar cada elemento de la array con la diferencia absoluta de las potencias más cercanas de A y B . Si existen dos potencias más cercanas, entonces elija el máximo de los dos.

Ejemplos:

Entrada: arr[] = {5, 12, 25}, A = 2, B = 3
Salida: 1 7 5
Explicación:

  • Para el elemento arr[0]( = 5): La potencia de 2 más cercana es 4 y la potencia de 3 más cercana es 3. Por lo tanto, la diferencia absoluta de 4 y 3 es 1.
  • Para arr[1]( = 12): La potencia más cercana de 2 es 16 y la potencia más cercana de 3 es 9. Por lo tanto, la diferencia absoluta de 16 y 9 es 7.
  • Para arr[2]( = 5): La potencia más cercana de 2 es 32 y la potencia más cercana de 3 es 27. Por lo tanto, la diferencia absoluta de 27 y 32 es 5.

Por lo tanto, la array modificada es {1, 7, 5}.

Entrada: arr[] = {32, 3, 7}, a = 2, b = 3
Salida: 0 1 1

Enfoque: el problema dado se puede resolver encontrando la potencia más cercana de A y B para cada elemento de la array y actualizándola a la diferencia absoluta de los dos valores obtenidos. 
Sigue los pasos para resolver el problema

  • Recorra la array dada arr[] y realice los siguientes pasos:
    • Encuentra los dos valores que son las potencias perfectas de a menor que y mayor que arr[i] y encuentra el más cercano de los dos valores.
    • Encuentra los dos valores que son las potencias perfectas de b menor que y mayor que arr[i] y encuentra el más cercano de los dos valores.
    • Encuentre la diferencia absoluta entre los dos valores más cercanos obtenidos y actualice arr[i] con ella.
  • Después de completar los pasos anteriores, imprima la array modificada arr[] .

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 array
void printArray(int arr[], int N)
{
    // Traverse the array
    for (int i = 0; i < N; i++) {
        cout << arr[i] << " ";
    }
}
 
// Function to modify array elements
// by absolute difference of the
// nearest perfect power of a and b
void nearestPowerDiff(int arr[], int N,
                      int a, int b)
{
    // Traverse the array arr[]
    for (int i = 0; i < N; i++) {
 
        // Find the log a of arr[i]
        int log_a = log(arr[i]) / log(a);
 
        // Find the power of a less
        // than and greater than a
        int A = pow(a, log_a);
        int B = pow(a, log_a + 1);
 
        if ((arr[i] - A) < (B - arr[i]))
            log_a = A;
        else
            log_a = B;
 
        // Find the log b of arr[i]
        int log_b = log(arr[i]) / log(b);
 
        // Find the power of b less than
        // and greater than b
        A = pow(b, log_b);
        B = pow(b, log_b + 1);
 
        if ((arr[i] - A) < (B - arr[i]))
            log_b = A;
        else
            log_b = B;
 
        // Update arr[i] with absolute
        // difference of log_a & log _b
        arr[i] = abs(log_a - log_b);
    }
 
    // Print the modified array
    printArray(arr, N);
}
 
// Driver Code
int main()
{
    int arr[] = { 5, 12, 25 };
    int A = 2, B = 3;
    int N = sizeof(arr) / sizeof(arr[0]);
 
    nearestPowerDiff(arr, N, A, B);
 
    return 0;
}

Java

// Java program for the above approach
import java.io.*;
 
class GFG{
 
// Function to print the array
static void printArray(int[] arr, int N)
{
     
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
        System.out.print(arr[i] + " ");
    }
}
 
// Function to modify array elements
// by absolute difference of the
// nearest perfect power of a and b
static void nearestPowerDiff(int[] arr, int N,
                             int a, int b)
{
     
    // Traverse the array arr[]
    for(int i = 0; i < N; i++)
    {
         
        // Find the log a of arr[i]
        int log_a = (int)(Math.log(arr[i]) /
                          Math.log(a));
 
        // Find the power of a less
        // than and greater than a
        int A = (int)(Math.pow(a, log_a));
        int B = (int)(Math.pow(a, log_a + 1));
 
        if ((arr[i] - A) < (B - arr[i]))
            log_a = A;
        else
            log_a = B;
 
        // Find the log b of arr[i]
        int log_b = (int)(Math.log(arr[i]) /
                          Math.log(b));
 
        // Find the power of b less than
        // and greater than b
        A = (int)(Math.pow(b, log_b));
        B = (int)(Math.pow(b, log_b + 1));
 
        if ((arr[i] - A) < (B - arr[i]))
            log_b = A;
        else
            log_b = B;
 
        // Update arr[i] with absolute
        // difference of log_a & log _b
        arr[i] = Math.abs(log_a - log_b);
    }
 
    // Print the modified array
    printArray(arr, N);
}
 
// Driver Code
public static void main(String[] args)
{
    int[] arr = { 5, 12, 25 };
    int A = 2, B = 3;
    int N = arr.length;
 
    nearestPowerDiff(arr, N, A, B);
}
}
 
// This code is contributed by subham348

Python3

# Python3 program for the above approach
import math
 
# Function to print the array
def printArray(arr, N):
     
    # Traverse the array
    for i in range(N):
        print(arr[i], end = " ")
     
# Function to modify array elements
# by absolute difference of the
# nearest perfect power of a and b
def nearestPowerDiff(arr, N, a, b):
     
    # Traverse the array arr[]
    for i in range(N):
 
        # Find the log a of arr[i]
        log_a = int(math.log(arr[i]) /
                    math.log(a))
 
        # Find the power of a less
        # than and greater than a
        A = int(pow(a, log_a))
        B = int(pow(a, log_a + 1))
 
        if ((arr[i] - A) < (B - arr[i])):
            log_a = A
        else:
            log_a = B
 
        # Find the log b of arr[i]
        log_b = int(math.log(arr[i]) /
                    math.log(b))
 
        # Find the power of b less than
        # and greater than b
        A = int(pow(b, log_b))
        B = int(pow(b, log_b + 1))
 
        if ((arr[i] - A) < (B - arr[i])):
            log_b = A
        else:
            log_b = B
 
        # Update arr[i] with absolute
        # difference of log_a & log _b
        arr[i] = abs(log_a - log_b)
     
    # Print the modified array
    printArray(arr, N)
 
# Driver Code
arr = [ 5, 12, 25 ]
A = 2
B = 3
N = len(arr)
 
nearestPowerDiff(arr, N, A, B)
 
# This code is contributed by sanjoy_62

C#

// C# program for the above approach
using System;
 
public class GFG{
 
// Function to print the array
static void printArray(int[] arr, int N)
{
     
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
        Console.Write(arr[i] + " ");
    }
}
 
// Function to modify array elements
// by absolute difference of the
// nearest perfect power of a and b
static void nearestPowerDiff(int[] arr, int N,
                             int a, int b)
{
     
    // Traverse the array arr[]
    for(int i = 0; i < N; i++)
    {
         
        // Find the log a of arr[i]
        int log_a = (int)(Math.Log(arr[i]) /
                          Math.Log(a));
 
        // Find the power of a less
        // than and greater than a
        int A = (int)(Math.Pow(a, log_a));
        int B = (int)(Math.Pow(a, log_a + 1));
 
        if ((arr[i] - A) < (B - arr[i]))
            log_a = A;
        else
            log_a = B;
 
        // Find the log b of arr[i]
        int log_b = (int)(Math.Log(arr[i]) /
                          Math.Log(b));
 
        // Find the power of b less than
        // and greater than b
        A = (int)(Math.Pow(b, log_b));
        B = (int)(Math.Pow(b, log_b + 1));
 
        if ((arr[i] - A) < (B - arr[i]))
            log_b = A;
        else
            log_b = B;
 
        // Update arr[i] with absolute
        // difference of log_a & log _b
        arr[i] = Math.Abs(log_a - log_b);
    }
 
    // Print the modified array
    printArray(arr, N);
}
 
// Driver Code
public static void Main(string[] args)
{
    int[] arr = { 5, 12, 25 };
    int A = 2, B = 3;
    int N = arr.Length;
 
    nearestPowerDiff(arr, N, A, B);
}
}
 
// This code is contributed by AnkThon

Javascript

<script>
 
// JavaScript implementation of the above approach
 
// Function to print the array
function printArray(arr, N)
{
      
    // Traverse the array
    for(let i = 0; i < N; i++)
    {
        document.write(arr[i] + " ");
    }
}
  
// Function to modify array elements
// by absolute difference of the
// nearest perfect power of a and b
function nearestPowerDiff(arr, N,
                             a, b)
{
      
    // Traverse the array arr[]
    for(let i = 0; i < N; i++)
    {
          
        // Find the log a of arr[i]
        let log_a = Math.floor(Math.log(arr[i]) /
                          Math.log(a));
  
        // Find the power of a less
        // than and greater than a
        let A = Math.floor(Math.pow(a, log_a));
        let B = Math.floor(Math.pow(a, log_a + 1));
  
        if ((arr[i] - A) < (B - arr[i]))
            log_a = A;
        else
            log_a = B;
  
        // Find the log b of arr[i]
        let log_b = Math.floor(Math.log(arr[i]) /
                          Math.log(b));
  
        // Find the power of b less than
        // and greater than b
        A = Math.floor(Math.pow(b, log_b));
        B = Math.floor(Math.pow(b, log_b + 1));
  
        if ((arr[i] - A) < (B - arr[i]))
            log_b = A;
        else
            log_b = B;
  
        // Update arr[i] with absolute
        // difference of log_a & log _b
        arr[i] = Math.abs(log_a - log_b);
    }
  
    // Print the modified array
    printArray(arr, N);
}
  
 
// Driver code
         
        let arr = [ 5, 12, 25 ];
    let A = 2, B = 3;
    let N = arr.length;
  
    nearestPowerDiff(arr, N, A, B);
     
    // This code is contributed by susmitakundugoaldanga.
</script>
Producción: 

1 7 5

 

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

Publicación traducida automáticamente

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