Kaprekar's Constant

After seeing a challenge on SQL Server Central to create an SQL solution to Kaprekar's constant, we decided to give it a shot. However we did not try to implement this in MS-SQL, instead we used C#.

Kaprekar's Constant is the magic number 6174 and states: That any number that is 4 digits in length (zero padded if less than four digits), the resulting number each digit is then sorted ascending and descending and re-assembled to each many an integer. The larger number is subtracted from the smaller and if the number is equal to the constant, then exit the routine. This routine should take no more than seven recursions for any given four digit number.

 public string KaprekarConstant(int intP, ref string p_strValues)
    {
        int intX = 0;
        int intY = 0;
        int intNewValue = -1;
        string strValues = intP.ToString().PadLeft(4, '0');

        int[] p1 = { Convert.ToInt32(strValues[0].ToString()), Convert.ToInt32(strValues[1].ToString()), Convert.ToInt32(strValues[2].ToString()), Convert.ToInt32(strValues[3].ToString()) };

        Array.Sort(p1);

        intX = Convert.ToInt32(p1[0].ToString() + p1[1].ToString() + p1[2].ToString() + p1[3].ToString());
        intY = Convert.ToInt32(p1[3].ToString() + p1[2].ToString() + p1[1].ToString() + p1[0].ToString());

        if (intY > intX)
        {
            intNewValue = intY - intX;
        }
        else
        {
            intNewValue = intX - intY;
        }
        p_strValues += intNewValue.ToString() + ", ";

        if (intNewValue != 6174)
        {
            KaprekarConstant(intNewValue, ref  p_strValues);
        }
        return p_strValues.Substring(0, p_strValues.Length - 2);

    }

References: http://en.wikipedia.org/wiki/6174_(number)

Newsletter Sign-up

Join our newsletter for product information and updates.