Constante de Kaprekar

6174 es la constante de Kaprekar. Este número es especial ya que siempre obtenemos este número cuando se siguen los siguientes pasos para cualquier número de cuatro dígitos, de modo que todos los dígitos del número no sean iguales, es decir, todos los números de cuatro dígitos excluyendo (0000, 1111, …)
 

  1. Ordene cuatro dígitos en orden ascendente y almacene el resultado en un número «asc».
  2. Ordene cuatro dígitos en orden descendente y almacene el resultado en un número «desc».
  3. Resta el número más grande del número más pequeño, es decir, abs (asc – desc).
  4. Repita los tres pasos anteriores hasta que el resultado de la resta no sea igual al número anterior.

Siempre terminamos con 6174. El
siguiente es el programa para demostrar lo mismo. 
 

C++

// C++ program to demonstrate working of
// Kaprekar constant
#include<bits/stdc++.h>
using namespace std;
 
// This function checks validity of kaprekar's
// constant. It returns kaprekar's constant for
// any four digit number "n" such that all digits
// of n are not same.
int kaprekarRec(int n, int &prev)
{
    if (n == 0)
       return 0;
 
    // Store current n as previous number
    prev = n;
 
    // Get four digits of given number
    int digits[4];
    for (int i=0; i<4; i++)
    {
       digits[i] = n%10;
       n = n/10;
    }
 
    // Sort all four digits in ascending order
    // And giet in the form of number "asc"
    sort(digits, digits+4);
    int asc = 0;
    for (int i=0; i<4; i++)
       asc = asc*10 + digits[i];
 
    // Get all four digits in descending order
    // in the form of number "desc"
    sort(digits, digits+4, std::greater<int> ());
    int desc = 0;
    for (int i=0; i<4; i++)
       desc = desc*10 + digits[i];
 
    // Get the difference of two numbers
    int diff = abs(asc - desc);
 
    // If difference is same as previous, we have
    // reached kaprekar's constant
    if (diff == prev)
        return diff;
 
    // Else recur
    return kaprekarRec(diff, prev);
}
 
// A wrapper over kaprekarRec()
int kaprekar(int n)
{
    int prev = 0;
    return kaprekarRec(n, prev);
}
 
// Driver code
int main()
{
    // Trying few four digit numbers, we
    // always get 6174
    cout << kaprekar(1000) << endl;
    cout << kaprekar(1112) << endl;
    cout << kaprekar(9812) << endl;
    return 0;
}

Java

// Java program to demonstrate working of
// Kaprekar constant
import java.util.Arrays;
 
class GFG{
// This function checks validity of kaprekar's
// constant. It returns kaprekar's constant for
// any four digit number "n" such that all digits
// of n are not same.
static int kaprekarRec(int n, int prev)
{
    if (n == 0)
    return 0;
 
    // Store current n as previous number
    prev = n;
 
    // Get four digits of given number
    int[] digits=new int[4];
    for (int i=0; i<4; i++)
    {
    digits[i] = n%10;
    n = n/10;
    }
 
    // Sort all four digits in ascending order
    // And giet in the form of number "asc"
    Arrays.sort(digits);
    int asc = 0;
    for (int i=0; i<4; i++)
    asc = asc*10 + digits[i];
 
    // Get all four digits in descending order
    // in the form of number "desc"
    Arrays.sort(digits);
    int desc = 0;
    for (int i=3; i>=0; i--)
    desc = desc*10 + digits[i];
 
    // Get the difference of two numbers
    int diff = Math.abs(asc - desc);
 
    // If difference is same as previous, we have
    // reached kaprekar's constant
    if (diff == prev)
        return diff;
 
    // Else recur
    return kaprekarRec(diff, prev);
}
 
// A wrapper over kaprekarRec()
static int kaprekar(int n)
{
    int prev = 0;
    return kaprekarRec(n, prev);
}
 
// Driver code
public static void main(String[] args)
{
    // Trying few four digit numbers, we
    // always get 6174
    System.out.println(kaprekar(1000));
    System.out.println(kaprekar(1112));
    System.out.println(kaprekar(9812));
}
}
// This code is contributed by mits

Python3

# Python3 program to demonstrate
# working of Kaprekar constant
 
# This function checks validity of
# kaprekar's constant. It returns
# kaprekar's constant for any four
# digit number "n" such that all
# digits of n are not same.
def kaprekarRec(n, prev):
 
    if (n == 0):
        return 0;
 
    # Store current n as previous
    # number
    prev = n;
 
    # Get four digits of given number
    digits = [0] * 4;
    for i in range(4):
        digits[i] = n % 10;
        n = int(n / 10);
 
    # Sort all four digits in ascending order
    # And giet in the form of number "asc"
    digits.sort();
    asc = 0;
    for i in range(4):
        asc = asc * 10 + digits[i];
 
    # Get all four digits in descending order
    # in the form of number "desc"
    digits.sort();
    desc = 0;
    for i in range(3, -1, -1):
        desc = desc * 10 + digits[i];
 
    # Get the difference of two numbers
    diff = abs(asc - desc);
 
    # If difference is same as previous,
    # we have reached kaprekar's constant
    if (diff == prev):
        return diff;
 
    # Else recur
    return kaprekarRec(diff, prev);
 
# A wrapper over kaprekarRec()
def kaprekar(n):
 
    rev = 0;
    return kaprekarRec(n, rev);
 
# Driver code
 
# Trying few four digit numbers, 
# we always get 6174
print(kaprekar(1000));
print(kaprekar(1112));
print(kaprekar(9812));
 
# This code is contributed by mits.

C#

// C# program to demonstrate working of
// Kaprekar constant
using System;
 
class GFG{
// This function checks validity of kaprekar's
// constant. It returns kaprekar's constant for
// any four digit number "n" such that all digits
// of n are not same.
static int kaprekarRec(int n, int prev)
{
    if (n == 0)
    return 0;
 
    // Store current n as previous number
    prev = n;
 
    // Get four digits of given number
    int[] digits=new int[4];
    for (int i=0; i<4; i++)
    {
    digits[i] = n%10;
    n = n/10;
    }
 
    // Sort all four digits in ascending order
    // And giet in the form of number "asc"
    Array.Sort(digits);
    int asc = 0;
    for (int i=0; i<4; i++)
    asc = asc*10 + digits[i];
 
    // Get all four digits in descending order
    // in the form of number "desc"
    Array.Sort(digits);
    int desc = 0;
    for (int i=3; i>=0; i--)
    desc = desc*10 + digits[i];
 
    // Get the difference of two numbers
    int diff = Math.Abs(asc - desc);
 
    // If difference is same as previous, we have
    // reached kaprekar's constant
    if (diff == prev)
        return diff;
 
    // Else recur
    return kaprekarRec(diff, prev);
}
 
// A wrapper over kaprekarRec()
static int kaprekar(int n)
{
    int prev = 0;
    return kaprekarRec(n, prev);
}
 
// Driver code
public static void Main()
{
    // Trying few four digit numbers, we
    // always get 6174
    System.Console.WriteLine(kaprekar(1000));
    System.Console.WriteLine(kaprekar(1112));
    System.Console.WriteLine(kaprekar(9812));
}
}
// This code is contributed by mits

PHP

<?php
// PHP program to demonstrate working of
// Kaprekar constant
 
// This function checks validity of kaprekar's
// constant. It returns kaprekar's constant
// for any four digit number "n" such that
// all digits of n are not same.
function kaprekarRec($n, $prev)
{
    if ($n == 0)
    return 0;
 
    // Store current n as previous number
    $prev = $n;
 
    // Get four digits of given number
    $digits = array_fill(0, 4, 0);
    for ($i = 0; $i < 4; $i++)
    {
        $digits[$i] = $n % 10;
        $n = (int)($n / 10);
    }
 
    // Sort all four digits in ascending order
    // And giet in the form of number "asc"
    sort($digits);
    $asc = 0;
    for ($i = 0; $i < 4; $i++)
    $asc = $asc * 10 + $digits[$i];
 
    // Get all four digits in descending order
    // in the form of number "desc"
    rsort($digits);
    $desc = 0;
    for ($i = 0; $i < 4; $i++)
    $desc = $desc * 10 + $digits[$i];
 
    // Get the difference of two numbers
    $diff = abs($asc - $desc);
 
    // If difference is same as previous,
    // we have reached kaprekar's constant
    if ($diff == $prev)
        return $diff;
 
    // Else recur
    return kaprekarRec($diff, $prev);
}
 
// A wrapper over kaprekarRec()
function kaprekar($n)
{
    $rev = 0;
    return kaprekarRec($n, $rev);
}
 
// Driver code
 
// Trying few four digit numbers, we
// always get 6174
echo kaprekar(1000) . "\n";
echo kaprekar(1112) . "\n";
echo kaprekar(9812) . "\n";
 
// This code is contributed by mits.
?>

Javascript

<script>
 
// Javascript program to demonstrate working of
// Kaprekar constant
 
// This function checks validity of kaprekar's
// constant. It returns kaprekar's constant for
// any four digit number "n" such that all digits
// of n are not same.
function kaprekarRec(n , prev)
{
    if (n == 0)
    return 0;
 
    // Store current n as previous number
    prev = n;
 
    // Get four digits of given number
    var digits= Array.from({length: 4}, (_, i) => 0);
    for (i=0; i<4; i++)
    {
    digits[i] = n%10;
    n = parseInt(n/10);
    }
 
    // Sort all four digits in ascending order
    // And giet in the form of number "asc"
    digits.sort();
    var asc = 0;
    for (i=0; i<4; i++)
    asc = asc*10 + digits[i];
 
    // Get all four digits in descending order
    // in the form of number "desc"
    digits.sort();
    var desc = 0;
    for (i=3; i>=0; i--)
    desc = desc*10 + digits[i];
 
    // Get the difference of two numbers
    var diff = Math.abs(asc - desc);
 
    // If difference is same as previous, we have
    // reached kaprekar's constant
    if (diff == prev)
        return diff;
 
    // Else recur
    return kaprekarRec(diff, prev);
}
 
// A wrapper over kaprekarRec()
function kaprekar(n)
{
    var prev = 0;
    return kaprekarRec(n, prev);
}
 
// Driver code
 
//Trying few four digit numbers, we
// always get 6174
document.write(kaprekar(1000)+"<br>");
document.write(kaprekar(1112)+"<br>");
document.write(kaprekar(9812)+"<br>");
 
 
// This code contributed by Princi Singh
 
</script>

Producción : 

6174
6174
6174

Ilustración : 
 

n = 2324
1) asc  = 2234
2) desc = 4322
3) Difference = 2088 
4) Repeating above steps as difference is not same
as n

n = 2088
1) asc  = 0288
2) desc = 8820
3) Difference = 8532  
4) Repeating above steps as difference is not same
as n.

n = 8532
1) asc  = 2358
2) desc = 8532
3) Difference = 6174  
4) Repeating above steps as difference is not same
as n.

n = 6174
1) asc  = 1467
2) desc = 7641
3) Difference = 6174  
Stopping here as difference is same as n.

Complejidad de tiempo : O (nlogn) donde n es el número de dígitos.

Referencia: 
https://en.wikipedia.org/wiki/6174_(number)
Artículo relacionado:  
Número de Kaprekar
Este artículo es una contribución de Gaurav Saxena . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.
Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.
 

Publicación traducida automáticamente

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