BTW: I saw a possible error in my last iteration. takeWhile (<n) is not proven to be correct. It's better to do it that way:
isKaprekarbasen=letsqr=n^2inelem0$-- any remainder = 0? <=> is kaprekar!map(\div->(sqr-n)`mod`(div-1))$-- compute the critical remainderstakeWhile(<sqr)$dropWhile(<=n)$-- sensible bounds for divisorsmap(base^)[1..]-- infinite list of divisorsmain=print$1:(filter(isKaprekar10)[1..10^5])
Also, it's nicer to use upper and lower bounds for divisors before computing the devisions. This is proven to be correct now, but I lost speed. ;-) The speed improvement by melting construction and restriction together is only 86% instead of 96%.
Use fixed-width Ints instead of arbitrary sized Integers (by function signature) Large improvement!
It pays off to spend an additional modulo division if the number of possible divisors for the critical division can be heavily reduced.
'any' slightly outperforms 'elem'. (in this case?)
A hand-rolled recursion sometimes performs better (without additional division) and sometimes worse (with additional division) than the folding recursions hidden in the 'elem' or 'any' functions. (But code with builtin folds is much nicer to read.)
The improvement steps were: 1000s - 500s - 90s - 60s - 19s - 13s - 9s. Quite funny to squeeze the algorithm like that. :-) This is what I came up with:
isKaprekar::Int->Int->BoolisKaprekarbasen=letsqr=n^2inany(\div->(sqr-n)`mod`(div-1)==0)$-- any rem = 0? <=> kaprekar!takeWhile(\div->(sqr`mod`div)<n)$-- sensible bounds for divisorsdropWhile(<=n)$map(base^)[1..]-- infinite list of divisorsmain=print$1:(filter(isKaprekar10)[1..10^8])
I wanted to have it in C for reference. Even expressed imperatively, it is now a very simple and nice algorithm. (2-3s)
I love seeing the iterations of your solutions. Not that this challenge was intended to have any "winners," but if we had to choose...
Do you have any ideas for new #challenge posts?
Thanks. I enjoyed learning about Kaprekar number as well as I enjoyed iterating my solutions as I digged deeper into it.
You encouraged me to pose a challenge, hoping it's not too easy and not too hard. dev.to/heikodudzus/challenge---pri...
BTW: I saw a possible error in my last iteration. takeWhile (<n) is not proven to be correct. It's better to do it that way:
Also, it's nicer to use upper and lower bounds for divisors before computing the devisions. This is proven to be correct now, but I lost speed. ;-) The speed improvement by melting construction and restriction together is only 86% instead of 96%.
Some last improvements:
The improvement steps were: 1000s - 500s - 90s - 60s - 19s - 13s - 9s. Quite funny to squeeze the algorithm like that. :-) This is what I came up with:
I wanted to have it in C for reference. Even expressed imperatively, it is now a very simple and nice algorithm. (2-3s)
C profited more by the additional division, it reduced the execution time by 75%, Haskell profited only by 50 %.
I hope, I'm really done, now. :)