Official

C - Kaprekar Number Editorial by en_translator


We can create three functions just as directed in the problem statement, and calculate in order. In many languages, one can implement \(g_1\) and \(g_2\) easily if you “convert the number to a string, sort, and convert it back to a number.”

Sample Code (Python)

def g1(n):
    return int(''.join(sorted(str(n))[::-1]))

def g2(n):
    return int(''.join(sorted(str(n))))

def f(n):
    return g1(n)-g2(n)

N,K = map(int,input().split())
for _ in range(K):
    N = f(N)
print(N)

Sample Code (C)

#include<stdio.h>
int f(int n){
	int c[20]={};
	while(n){
		c[n%10]++;
		n/=10;
	}
	int g1=0,g2=0;
	for(int i=9;i>=0;i--)for(int j=0;j<c[i];j++)g1=g1*10+i;
	for(int i=0;i<=9;i++)for(int j=0;j<c[i];j++)g2=g2*10+i;
	return g1-g2;
}

int main(){
	int n,k;
	scanf("%d%d",&n,&k);
	for(int i=0;i<k;i++)n=f(n);
	printf("%d\n",n);
}

posted:
last update: