Saturday, March 27, 2021

 6174 is known as Kaprekar's constant. My friend Ayaz, had shared this with me. I thought of writing a program in python to check and find out the number with the max interations to reach 6174. The program is here. You can read more about Karekar's constant in the wiki article. Click here



def allnums(n):

    res = [int(x) for x in str(n)]

    if (res[0]==res[1] & res[1]==res[2] & res[2]==res[3]):

        return (0)


def kaprekar(m):

    lp=0

    n=m

    while (n != 6174):

        integers = [int(x) for x in str(n)]

        integers.sort(reverse=True)

        strings = [str(integer) for integer in integers]

        a_string = "".join(strings)

        a = int(a_string)

        if a < 1000:

            a=a*10

        integers.sort()

        str2 = [str(integer) for integer in integers]

        str3 = "".join(str2)

        b = int(str3)   

        n=a-b

        lp=lp+1

    return(lp)

######################################## program starts here

mx=0

mxn=1000

for x in range(1000,9999):

    if allnums(x)!=0:

        y=kaprekar(x)

        if (y > mx):

            mx=y

            mxn=x

print(mx,mxn)




==========================================================================

Run the program and the output is

7 1004

1004 is the first number that needs 7 iterations to reach 6174.