Kaprekar’s constant is a curiousity where the number 6174 recurs again and again if you take any four digit number ( with some conditions ) and follow an algorithm. It’s best explained on the web and it’s a pretty simple algorithm. My exercise here is to have ChatGPT code the entire algorithm for me and test if it can code it correctly.
Outline
I first broke down the steps needed. The code needed to select a random number, test it for conditions and keep running the algorithm until 6174 showed up. The basic functions I needed ChatGPT to construct were
- generate a random 4 digit number
- test for at least 2 unique numbers in the 4 digit number
- Reorder the numbers in descending order for one number and in ascending order for another.
Here we go.
Generate random 4 digit number

This was simple enough. It even provided an explanation for the function it created. This occurred for all the code it generated. You won’t see it in subsequent screenshots out of brevity.
Code to test for at least 2 unique numbers in the 4 digit number

and finally
Reorder numbers in descending or ascending order

Putting it altogether
def start():
print("Start algol")
doesQualify = False
while(not doesQualify):
# Do random number
num = random.randint(1000, 10000)
print("Generate random number: " + str(num))
# Check at least two distinct digits
if has_at_least_2_distinct_digits(num):
doesQualify = True
isDone = False
while(not isDone):
topNum = sort_number(num);
bottomNum = sort_number(num, False)
resultNum = int(topNum) - int(bottomNum)
print("Result: " + topNum + " - " + bottomNum + " = " + str(resultNum))
if (resultNum == 6174):
isDone = True
else:
num = resultNum
and viola…it works
Start algol
Generate random number: 1022
Result: 2210 – 0122 = 2088
Result: 8820 – 0288 = 8532
Result: 8532 – 2358 = 6174
Process finished with exit code 0
Summary
I did all this in about 30 minutes. Next is to try it different languages and move on to more complex assignments, but so far I’m pretty impressed.
Pingback: It all seems so quaint – looking back at posts from 3 years ago | numbersandcode