Kaprekar Constant | Java program to demonstrate working of 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 ( ) ; Driver code ; Trying few four digit numbers , we always get 6174
import java . util . Arrays ; class GFG { static int kaprekarRec ( int n , int prev ) { if ( n == 0 ) return 0 ; prev = n ; int [ ] digits = new int [ 4 ] ; for ( int i = 0 ; i < 4 ; i ++ ) { digits [ i ] = n % 10 ; n = n / 10 ; } Arrays . sort ( digits ) ; int asc = 0 ; for ( int i = 0 ; i < 4 ; i ++ ) asc = asc * 10 + digits [ i ] ; Arrays . sort ( digits ) ; int desc = 0 ; for ( int i = 3 ; i >= 0 ; i -- ) desc = desc * 10 + digits [ i ] ; int diff = Math . abs ( asc - desc ) ; if ( diff == prev ) return diff ; return kaprekarRec ( diff , prev ) ; } static int kaprekar ( int n ) { int prev = 0 ; return kaprekarRec ( n , prev ) ; } public static void main ( String [ ] args ) { System . out . println ( kaprekar ( 1000 ) ) ; System . out . println ( kaprekar ( 1112 ) ) ; System . out . println ( kaprekar ( 9812 ) ) ; } }