Code: Select all
' Kaprekar's constant 6174
'
' start with any 4 digit number, with at least 2 digits
' different from each other, and greater than 1000.
' Make two new numbers by sorting the number digits upward and
' downward.
' Calculate the difference and repeat the previous step with
' that difference.
' After a maximum of 7 steps the difference will become 6174
' and stays at that value
'
input "number (4 digits): ":n ' input a 4 digit number
dim a(4),b(4)
do
print n ' print the number to be processd
num2arr(n,a) ' convert to array a with the 4 digits
sort a ' sort the array a (descending)
revert(a,b) ' revert array a into ascending array b
dif=arr2num(b)-arr2num(a) ' convert into numbers & subtract
if dif=n then break else n=dif ' done if output = input
until forever
print dif
end
def num2arr(x,a())
n$=str$(x)
for i=0 to 3 ! a(i)=val(mid$(n$,i,1)) ! next i
end def
def revert(x(),y())
for i=0 to 3 ! y(3-i)=x(i) ! next i
end def
def arr2num(x())
res=0
for i=0 to 3 ! res+=10^(3-i)*x(i) ! next i
return res
end def
