Kaprekar Constant | C ++ 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 digits 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int kaprekarRec ( int n , int & prev ) { if ( n == 0 ) return 0 ; prev = n ; int digits [ 4 ] ; for ( int i = 0 ; i < 4 ; i ++ ) { digits [ i ] = n % 10 ; n = n / 10 ; } sort ( digits , digits + 4 ) ; int asc = 0 ; for ( int i = 0 ; i < 4 ; i ++ ) asc = asc * 10 + digits [ i ] ; sort ( digits , digits + 4 , std :: greater < int > ( ) ) ; int desc = 0 ; for ( int i = 0 ; i < 4 ; i ++ ) desc = desc * 10 + digits [ i ] ; int diff = abs ( asc - desc ) ; if ( diff == prev ) return diff ; return kaprekarRec ( diff , prev ) ; } int kaprekar ( int n ) { int prev = 0 ; return kaprekarRec ( n , prev ) ; } int main ( ) { cout << kaprekar ( 1000 ) << endl ; cout << kaprekar ( 1112 ) << endl ; cout << kaprekar ( 9812 ) << endl ; return 0 ; }