1 #include <iostream>
   2 #include <sstream>
   3 #include <string>
   4 #include <algorithm>
   5 #include <vector>
   6 #include <set>
   7 using namespace std;
   8 
   9 #define GI ({int _t; scanf("%d", &_t); _t;})
  10 #define FOR(i, a, b) for (int i=a; i<b; i++)
  11 #define REP(i, a) FOR(i, 0, a)
  12 template<class T> string toString(T n){ostringstream ost;ost<<n;ost.flush();return ost.str();}
  13 int toInt(string s){int r=0;istringstream sin(s);sin>>r;return r;}
  14 #define DBG(x) cout << #x << "::" << x << endl;
  15 #define DBGV(_v) { REP(_i, _v.size()) { cout << _v[_i] << "\t";} cout << endl;}
  16 #define sz size()
  17 
  18 string format(string number) {
  19 	while (number[0] == '0' && number.sz > 1) { number = number.substr(1); }
  20 	return number;
  21 }
  22 
  23 string sub (string s1, string s2) {
  24 	// Returns (s1 - s2)
  25 	// Works if s1 > s2
  26 	bool borrow = false;
  27 	int cur = 0;
  28 	string res = "";
  29 	reverse(s1.begin(), s1.end());
  30 	reverse(s2.begin(), s2.end());
  31 	for (int i=0; i < s1.sz ; i++) {
  32 		cur = 0;
  33 		if ( i < s2.sz) { cur = s1[i] - s2[i]; }
  34 		else { cur = s1[i] - '0'; }
  35 		if (cur < 0) {
  36 			cur += 10;
  37 			for (int j=i+1; j < s1.sz ; j++) {
  38 				if (s1[j] == '0') { s1[j] = '9'; }
  39 				else { s1[j] -= 1; break; }
  40 			}
  41 		}
  42 		res += (char)(cur+'0');
  43 	}
  44 	reverse(res.begin(), res.end());
  45 	//Remove leading zeroes
  46 	while (res[0] == '0' && res.sz > 1) { res = res.substr(1); }
  47 	return res;
  48 }
  49 
  50 int main() {
  51 	string number;
  52 	bool first = true;
  53 	while (1) {
  54 		cin >> number;
  55 		if (number == "0") break;
  56 		//if (first == false) printf("\n");
  57 		first = false;
  58 		set <string> list;
  59 		printf("Original number was %s\n", number.c_str());
  60 		int chain = 0;
  61 		while (1) {
  62 			chain++;
  63 			list.insert(number);
  64 			sort(number.begin(), number.end());
  65 			string max = number, min = number;
  66 			reverse(max.begin(), max.end());
  67 			number = sub(max, min);
  68 			printf("%s - %s = %s\n", format(max).c_str(), format(min).c_str(), number.c_str());
  69 			if (list.find(number) != list.end()) {
  70 				printf("Chain length %d\n", chain);
  71 				break;
  72 			}
  73 		}
  74 		printf("\n");
  75 	}
  76 	return 0;
  77 }