Número de cubo perfecto más grande en una array

Dada una array de N enteros. La tarea es encontrar el número más grande que es un cubo perfecto. Imprime -1 si no hay ningún número que sea cubo perfecto.
Ejemplos
 

Input : arr[] = {16, 8, 25, 2, 3, 10} 
Output : 25
Explanation: 25 is the largest number 
that is a perfect cube. 

Input : arr[] = {36, 64, 10, 16, 29, 25| 
Output : 64

Una solución simple es ordenar los elementos y ordenar los números N y comenzar a buscar desde atrás un número de cubo perfecto usando la función cbrt(). El primer número desde el final, que es un número cúbico perfecto, es nuestra respuesta. La complejidad de clasificación es O(n log n) y de la función cbrt() es log n, por lo que en el peor de los casos la complejidad es O(n log n).
Una Solución Eficiente es iterar para todos los elementos en O(n) y comparar cada vez con el elemento máximo, y almacenar el máximo de todos los cubos perfectos.
A continuación se muestra la implementación del enfoque anterior: 
 

C++

// CPP program to find the largest perfect
// cube number among n numbers
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if a number
// is perfect cube number or not
bool checkPerfectcube(int n)
{
    // takes the sqrt of the number
    int d = cbrt(n);
 
    // checks if it is a perfect
    // cube number
    if (d * d * d == n)
        return true;
 
    return false;
}
 
// Function to find the largest perfect
// cube number in the array
int largestPerfectcubeNumber(int a[], int n)
{
    // stores the maximum of all
    // perfect cube numbers
    int maxi = -1;
 
    // Traverse all elements in the array
    for (int i = 0; i < n; i++) {
 
        // store the maximum if current
        // element is a perfect cube
        if (checkPerfectcube(a[i]))
            maxi = max(a[i], maxi);
    }
 
    return maxi;
}
 
// Driver Code
int main()
{
    int a[] = { 16, 64, 25, 2, 3, 10 };
 
    int n = sizeof(a) / sizeof(a[0]);
 
    cout << largestPerfectcubeNumber(a, n);
 
    return 0;
}

C

// C program to find the largest perfect
// cube number among n numbers
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
 
int max(int a, int b)
{
  int max = a;
  if(max < b)
    max = b;
  return max;
}
 
// Function to check if a number
// is perfect cube number or not
bool checkPerfectcube(int n)
{
    // takes the sqrt of the number
    int d = cbrt(n);
 
    // checks if it is a perfect
    // cube number
    if (d * d * d == n)
        return true;
 
    return false;
}
 
// Function to find the largest perfect
// cube number in the array
int largestPerfectcubeNumber(int a[], int n)
{
    // stores the maximum of all
    // perfect cube numbers
    int maxi = -1;
 
    // Traverse all elements in the array
    for (int i = 0; i < n; i++) {
 
        // store the maximum if current
        // element is a perfect cube
        if (checkPerfectcube(a[i]))
            maxi = max(a[i], maxi);
    }
 
    return maxi;
}
 
// Driver Code
int main()
{
    int a[] = { 16, 64, 25, 2, 3, 10 };
 
    int n = sizeof(a) / sizeof(a[0]);
 
    printf("%d",largestPerfectcubeNumber(a, n));
 
    return 0;
}
 
// This code is contributed by kothavvsaakash.

Java

// Java program to find the largest perfect
// cube number among n numbers
class Solution
{
 
// Function to check if a number
// is perfect cube number or not
static boolean checkPerfectcube(int n)
{
    // takes the sqrt of the number
    int d =(int) Math.cbrt(n);
 
    // checks if it is a perfect
    // cube number
    if (d * d * d == n)
        return true;
 
    return false;
}
 
// Function to find the largest perfect
// cube number in the array
static int largestPerfectcubeNumber(int a[], int n)
{
    // stores the maximum of all
    // perfect cube numbers
    int maxi = -1;
 
    // Traverse all elements in the array
    for (int i = 0; i < n; i++) {
 
        // store the maximum if current
        // element is a perfect cube
        if (checkPerfectcube(a[i]))
            maxi = Math.max(a[i], maxi);
    }
 
    return maxi;
}
 
// Driver Code
public static void main(String args[])
{
    int a[] = { 16, 64, 25, 2, 3, 10 };
 
    int n =a.length;
 
    System.out.print(largestPerfectcubeNumber(a, n));
 
}
}
 
//contributed by Arnab Kundu

Python3

# Python 3 program to find the largest
# perfect cube number among n numbers
import math
 
# Function to check if a number
# is perfect cube number or not
def checkPerfectcube(n):
     
    # checks if it is a perfect
    # cube number
    cube_root = n**(1./3.)
    if round(cube_root) ** 3 == n:
        return True
         
    else:
        return False
 
# Function to find the largest perfect
# cube number in the array
def largestPerfectcubeNumber(a, n):
     
    # stores the maximum of all
    # perfect cube numbers
    maxi = -1
 
    # Traverse all elements in the array
    for i in range(0, n, 1):
         
        # store the maximum if current
        # element is a perfect cube
        if (checkPerfectcube(a[i])):
            maxi = max(a[i], maxi)
 
    return maxi;
 
# Driver Code
if __name__ == '__main__':
    a = [16, 64, 25, 2, 3, 10]
 
    n = len(a)
 
    print(largestPerfectcubeNumber(a, n))
 
# This code is contributed by
# Surendra_Gangwar

C#

//C# program to find the largest perfect
// cube number among n numbers
using System;
 
public class Solution
{
 
    // Function to check if a number
    // is perfect cube number or not
    static bool checkPerfectcube(int n)
    {
        // takes the sqrt of the number
        int d = (int)Math.Ceiling(Math.Pow(n, (double)1 / 3));
        // checks if it is a perfect
        // cube number
        if (d * d * d == n)
            return true;
 
        return false;
    }
 
    // Function to find the largest perfect
    // cube number in the array
    static int largestPerfectcubeNumber(int []a, int n)
    {
        // stores the maximum of all
        // perfect cube numbers
        int maxi = -1;
 
        // Traverse all elements in the array
        for (int i = 0; i < n; i++) {
 
            // store the maximum if current
            // element is a perfect cube
            if (checkPerfectcube(a[i]))
                maxi = Math.Max(a[i], maxi);
        }
 
        return maxi;
    }
 
    // Driver Code
    public static void Main()
    {
        int []a = { 16, 64, 25, 2, 3, 10 };
 
        int n =a.Length;
 
        Console.WriteLine(largestPerfectcubeNumber(a, n));
 
    }
}
 
/*This code is contributed by PrinciRaj1992*/

PHP

<?php
// PHP program to find the largest perfect
// cube number among n numbers
 
// Function to check if a number
// is perfect cube number or not
function checkPerfectcube($n)
{
    // takes the sqrt of the number
    $d = pow($n, (1 / 3));
    $d = round($d);
 
    // checks if it is a perfect
    // cube number
    if ($d * $d * $d == $n)
        return true;
 
    return false;
}
 
// Function to find the largest perfect
// cube number in the array
function largestPerfectcubeNumber(&$a, $n)
{
    // stores the maximum of all
    // perfect cube numbers
    $maxi = -1;
 
    // Traverse all elements in the array
    for ($i = 0; $i < $n; $i++)
    {
 
        // store the maximum if current
        // element is a perfect cube
        if (checkPerfectcube($a[$i]))
            $maxi = max($a[$i], $maxi);
    }
 
    return $maxi;
}
 
// Driver Code
$a = array( 16, 64, 25, 2, 3, 10 );
$n = sizeof($a);
echo largestPerfectcubeNumber($a, $n);
 
// This code is contributed by ita_c
?>

Javascript

<script>
 
// Javascript program to find the largest perfect
// cube number among n numbers
 
// Function to check if a number
// is perfect cube number or not
function checkPerfectcube(n)
{
    // takes the sqrt of the number
    let d = parseInt(Math.cbrt(n));
 
    // checks if it is a perfect
    // cube number
    if (d * d * d == n)
        return true;
 
    return false;
}
 
// Function to find the largest perfect
// cube number in the array
function largestPerfectcubeNumber(a, n)
{
    // stores the maximum of all
    // perfect cube numbers
    let maxi = -1;
 
    // Traverse all elements in the array
    for (let i = 0; i < n; i++) {
 
        // store the maximum if current
        // element is a perfect cube
        if (checkPerfectcube(a[i]))
            maxi = Math.max(a[i], maxi);
    }
 
    return maxi;
}
 
// Driver Code
let a = [ 16, 64, 25, 2, 3, 10 ];
 
let n = a.length;
 
document.write(largestPerfectcubeNumber(a, n));
 
</script>
Producción: 

64

 

Publicación traducida automáticamente

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