#PROBLEM LINK:

https://www.codechef.com/TNP52021/problems/TNP502

*Author:* Setter’s Name

*Tester:* Tester’s Name

*Editorialist:* Editorialist’s name

DIFFICULTY : EASY

# PREREQUISITES:

Arrays and loops

#PROBLEM:

Due to the lockdown imposed as a result of the pandemic, Ramu is forced to stay in his home. For passing time he started playing with numbers.Interestingly, he found out a new pattern. He takes a 4-digit number (with at most 3-digits repeating), writes the largest and smallest number that can be obtained by rearranging the digits of that 4-digit number, finds the difference between the largest and smallest number, then on continuing this operation, eventually he will reach the number 6174.

For example, consider the number 1789. The largest number that can be obtained by rearranging the digits in 1789 is 9871 and the smallest is 1789.

Step 1: 9871-1789=8082

Step 2: 8820-0288=8532 (the largest number from 8082 is 8820 and smallest is 0288)

Step 3: 8532-2358=6174 (the largest number from 8532 is 8532 and smallest is 2358)

Eventually it will terminate in 6174. Even if we proceed further we will get 6174 (7614-1467=6174 , 7614 is the largest and 1467 is the smallest)

In the above example we can see that we reached 6174 by 3 steps. We can obtain 6174 from any 4-digit number by a maximum of 7 steps.

Ramu wants you to find out within how many steps 6174 can be obtained from the given inputs.

Note: All the four digits of the number shouldn’t be the same. At most 3 digits can repeat(the number can’t be 1111,2222 etc.)

#EXPLANATION:

Find the largest and smallest number from rearranging the digits of the given number. Then obtain it’s difference and increase the counter. If the difference equals 6174,then exit out of the loop and print the value of the counter variable. If it is not, then repeat the previous step until the difference reaches 6174.

#SOLUTION:

## Setter's Solution

#include<bits/stdc++.h>

using namespace std;

int main()

{

int t;

cin>>t;

while(t–)

{

int x;

cin>>x;

int count=0;

while(1)

{

int asc[4],dsc[4],max=0,min=0,diff;

for(int i=0;i<4;i++)

{

asc[i]=x%10;

dsc[i]=x%10;

x=x/10;

```
}
sort(asc,asc+4);
sort(dsc,dsc+4,greater<int>());
for(int i=0;i<4;i++)
max=max*10+dsc[i];
for(int i=0;i<4;i++)
min=min*10+asc[i];
diff=max-min;
if(diff==6174)
{
count++;
break;
}
else
{
count++;
x=diff;
}
}
cout<<count<<endl;
}
return 0;
```

}

## Tester's Solution

Same Person

## Editorialist's Solution

Same Person