Skip to content

Instantly share code, notes, and snippets.

@mbeltagy

mbeltagy/kaprekar.jl

Last active Apr 14, 2017
Embed
What would you like to do?
Kaprekar's constant from Numberphile
# 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment