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
function kaprekarRec ( n , prev ) { if ( n == 0 ) return 0 ; prev = n ; var digits = Array . from ( { length : 4 } , ( _ , i ) => 0 ) ; for ( i = 0 ; i < 4 ; i ++ ) { digits [ i ] = n % 10 ; n = parseInt ( n / 10 ) ; } digits . sort ( ) ; var asc = 0 ; for ( i = 0 ; i < 4 ; i ++ ) asc = asc * 10 + digits [ i ] ; digits . sort ( ) ; var desc = 0 ; for ( i = 3 ; i >= 0 ; i -- ) desc = desc * 10 + digits [ i ] ; var diff = Math . abs ( asc - desc ) ; if ( diff == prev ) return diff ; return kaprekarRec ( diff , prev ) ; } function kaprekar ( n ) { var prev = 0 ; return kaprekarRec ( n , prev ) ; } document . write ( kaprekar ( 1000 ) + " " ) ; document . write ( kaprekar ( 1112 ) + " " ) ; document . write ( kaprekar ( 9812 ) + " " ) ;