Kaprekar Constant | This function checks validity of kaprekar ' s ▁ constant . ▁ It ▁ returns ▁ kaprekar ' s constant for any four digit number " n " such that all digits of n are not same . ; Store current n as previous number ; Get four digits of given number ; Sort all four dgits in ascending order And giet in the form of number " asc " ; Get all four dgits in descending order in the form of number " desc " ; Get the difference of two numbers ; If difference is same as previous , we have reached kaprekar 's constant ; Else recur ; A wrapper over kaprekarRec ( ) ; Trying few four digit numbers , we always get 6174
< ? php function kaprekarRec ( $ n , $ prev ) { if ( $ n == 0 ) return 0 ; $ prev = $ n ; $ digits = array_fill ( 0 , 4 , 0 ) ; for ( $ i = 0 ; $ i < 4 ; $ i ++ ) { $ digits [ $ i ] = $ n % 10 ; $ n = ( int ) ( $ n / 10 ) ; } sort ( $ digits ) ; $ asc = 0 ; for ( $ i = 0 ; $ i < 4 ; $ i ++ ) $ asc = $ asc * 10 + $ digits [ $ i ] ; rsort ( $ digits ) ; $ desc = 0 ; for ( $ i = 0 ; $ i < 4 ; $ i ++ ) $ desc = $ desc * 10 + $ digits [ $ i ] ; $ diff = abs ( $ asc - $ desc ) ; if ( $ diff == $ prev ) return $ diff ; return kaprekarRec ( $ diff , $ prev ) ; } function kaprekar ( $ n ) { $ rev = 0 ; return kaprekarRec ( $ n , $ rev ) ; } echo kaprekar ( 1000 ) . " STRNEWLINE " ; echo kaprekar ( 1112 ) . " STRNEWLINE " ; echo kaprekar ( 9812 ) . " STRNEWLINE " ; ? >