#include<iostream>
#include<iomanip>
#include<string.h>
#include<string>
#include<algorithm>
#include<map>
#include<iterator>
#include<cmath>
#include<vector>
#include<utility>
#include<stack>
#include<queue>
#define li long int
#define ll long long int
#define lli unsigned long long int
#define mod 1e9+7
using namespace std;


int main() {
    std::ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int n,k;
    cin>>n>>k;
    for(int j=1; j<=k; j++){
        vector<int>v,m;
        while(n!=0){
            v.push_back(n%10);
            n/=10;
        }
        m=v;
        sort(v.begin(),v.end());
        sort(m.rbegin(),m.rend());
        int len=v.size(),len2;
        int num=0,num1=0;
        len--;
        len2=len;
        int p=pow(10,len),p1;
        int i=0;
        p1=p;
        while(len>=0){
            num+=v[i++]*p;
            p/=10;
            len--;
        }
        i=0;
        while(len2>=0){
            num1+=m[i++]*p1;
            p1/=10;
            len2--;
        }
        n=num1-num;
    }
    cout<<n<<endl;
    return 0;
}
#include <bits/stdc++.h>
using namespace std;

const int N = 20;

mt19937 mt;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    mt.seed(time(nullptr));
    int n, m;
    cin >> n >> m;
    vector<string> v(m);
    for (auto& i : v) {
        cin >> i;
    }
    //sort(v.begin(), v.end(), [](string a, string b){return a.size() < b.size();});
    shuffle(v.begin(), v.end(), mt);
    int ind[10] = {};
    for (auto& i : v) {
        for (auto& j : i) {
            ++ind[j - 'A'];
        }
    }
    char a[N][N];
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            a[i][j] = char(int(max_element(ind, ind + 10) - ind) + int('A'));
        }
    }
    int i = 0, j = 0;
    for (auto s : v) {
        if (j + s.size() >= n) {
            j = 0;
            ++i;
        }
        if (i >= n) {
            break;
        }
        for (int k = 0; k < s.size(); ++k, ++j) {
            a[i][j] = s[k];
        }
    }
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            cout << a[i][j];
        }
        cout << '\n';
    }
	return 0;
}
