01/13/17

# Kaperkar’s Constant

I was recently introduced to Kaperkar’s Constant.
It is quite magical. You take any four digit number $A$, sort the digits from highest to lowest to create a new number $A^{\text{high}}$, sort the digits from lowest to highest to get $A^{\text{low}}$, and calculate and new number $A= A^{\text{high}}- A^{\text{low}}$. You repeat this procedure enough times and you end up with $A=6174$.

I made a nifty implementation of that in Julia below.

 # We work out the Kaprekar's constant function breakdown(x::Int) y=[j for j in "\$x"] end function put_together(y::Vector{Char}) sum(parse(Int,y[i])*10^(i–1) for i=1:length(y)) end """ Finds a fixed point by the repeated appliction of subtracting the largest combination of digits from the smallest. Returns the fixed ponit and flag indicating of one was found or not. """ function find_fp(x) x_prev=0 for i=1:100 x_prev=x big=x|>breakdown|>sort|>put_together small=x|>breakdown|>z->sort(z,rev=true)|>put_together x=big–small (x==x_prev) && break end x,x==x_prev end find_fp(2241) # (6174,true)

view raw
kaprekar.jl
hosted with ❤ by GitHub