Dudeney Numbers

Опубликовано: 14 Января, 2022

Учитывая целое число n , задача состоит в том, чтобы проверить, является ли n числом Дудени или нет. Число Дудени - это положительное целое число, которое представляет собой идеальный куб, сумма десятичных цифр которого равна кубическому корню из числа.

Примеры:

Input: N = 19683
Output: Yes
19683 = 273 and 1 + 9 + 6 + 8 + 3 = 27

Input: N = 75742
Output: No

Рекомендуется: сначала попробуйте свой подход в {IDE}, прежде чем переходить к решению.

Подход:

  • Проверьте, является ли n идеальным кубом, если нет, то это не может быть число Дудени.
  • Если n - идеальный куб, вычислите сумму его цифр. Если сумма его цифр равна его кубическому корню, тогда это число Дудени, иначе это не так.

Below is the implementation of the above approach:

C++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// Function that returns true if
// n is a Dudeney number
bool isDudeney(int n)
{
    int cube_rt = int(round((pow(n, 1.0 / 3.0))));
  
    // If n is not a perfect cube
    if (cube_rt * cube_rt * cube_rt != n)
        return false;
  
    int dig_sum = 0;
    int temp = n;
    while (temp > 0) {
  
        // Last digit
        int rem = temp % 10;
  
        // Update the digit sum
        dig_sum += rem;
  
        // Remove the last digit
        temp /= 10;
    }
  
    // If cube root of n is not equal to
    // the sum of its digits
    if (cube_rt != dig_sum)
        return false;
  
    return true;
}
  
// Driver code
int main()
{
    int n = 17576;
    if (isDudeney(n))
        cout << "Yes";
    else
        cout << "No";
  
    return 0;
}

Java

// Java implementation of the approach
import java.lang.Math;
  
class GFG
{
      
// Function that returns true if
// n is a Dudeney number
static boolean isDudeney(int n)
{
    int cube_rt = (int)(Math.round((Math.pow(n, 1.0 / 3.0))));
  
    // If n is not a perfect cube
    if (cube_rt * cube_rt * cube_rt != n)
        return false;
  
    int dig_sum = 0;
    int temp = n;
    while (temp > 0)
    {
  
        // Last digit
        int rem = temp % 10;
  
        // Update the digit sum
        dig_sum += rem;
  
        // Remove the last digit
        temp /= 10;
    }
  
    // If cube root of n is not equal to
    // the sum of its digits
    if (cube_rt != dig_sum)
        return false;
  
    return true;
}
  
// Driver code
public static void main(String[] args)
{
    int n = 17576;
    if (isDudeney(n))
        System.out.println("Yes");
    else
        System.out.println("No");
}
}
  
// This code is contributed by Code_Mech.

Python3

# Python implementation of the approach
  
# Function that returns true if 
# n is a Dudeney number
def isDudeney(n):
    cube_rt = int(round((pow(n, 1.0 / 3.0))))
  
    # If n is not a perfect cube
    if cube_rt * cube_rt * cube_rt != n:
        return False
  
    dig_sum = 0
    temp = n
    while temp>0:
          
        # Last digit
        rem = temp % 10
          
        # Update the digit sum
        dig_sum += rem
          
        # Remove the last digit
        temp//= 10
  
    # If cube root of n is not equal to 
    # the sum of its digits
    if cube_rt != dig_sum:
        return False
  
    return True
  
# Driver code
if __name__ == "__main__":
      
    n = 17576
    if isDudeney(n):
        print("Yes")
    else:
        print("No")

C#

// C# implementation of the approach
using System;
  
class GFG
{
      
// Function that returns true if
// n is a Dudeney number
static bool isDudeney(int n)
{
    int cube_rt = (int)(Math.Round((Math.Pow(n, 1.0 / 3.0))));
  
    // If n is not a perfect cube
    if (cube_rt * cube_rt * cube_rt != n)
        return false;
  
    int dig_sum = 0;
    int temp = n;
    while (temp > 0)
    {
  
        // Last digit
        int rem = temp % 10;
  
        // Update the digit sum
        dig_sum += rem;
  
        // Remove the last digit
        temp /= 10;
    }
  
    // If cube root of n is not equal to
    // the sum of its digits
    if (cube_rt != dig_sum)
        return false;
  
    return true;
}
  
// Driver code
public static void Main()
{
    int n = 17576;
    if (isDudeney(n))
        Console.Write("Yes");
    else
        Console.Write("No");
}
}
  
// This code is contributed 
// by Akanksha Rai

PHP

<?php
// PHP implementation of the approach 
  
// Function that returns true if 
// n is a Dudeney number 
function isDudeney($n
    $cube_rt = floor(round((pow($n, 1.0 / 3.0)))); 
  
    // If n is not a perfect cube 
    if ($cube_rt * $cube_rt * $cube_rt != $n
        return false; 
  
    $dig_sum = 0; 
    $temp = $n
    while ($temp > 0) 
    
  
        // Last digit 
        $rem = $temp % 10; 
  
        // Update the digit sum 
        $dig_sum += $rem
  
        // Remove the last digit 
        $temp = $temp/10; 
    
  
    // If cube root of n is not equal to 
    // the sum of its digits 
    if ($cube_rt != $dig_sum
        return false; 
  
    return true; 
  
// Driver code 
$n = 17576; 
if (isDudeney($n)) 
    echo "Yes"
else
    echo "No";
  
// This code is contributed by Ryuga
?>
Output:
Yes

Вниманию читателя! Не прекращайте учиться сейчас. Освойте все важные концепции DSA с помощью самостоятельного курса DSA по приемлемой для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .

Если вы хотите посещать живые занятия с отраслевыми экспертами, пожалуйста, обращайтесь к Geeks Classes Live и Geeks Classes Live USA.