Last active
April 14, 2017 22:07
-
-
Save mbeltagy/b27f5cc93346d5e0614c92ab696dfc31 to your computer and use it in GitHub Desktop.
Kaprekar's constant from Numberphile
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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