Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

6174

Introduction
An interesting sequence of numbers can be generated using any given integer using
the following procedure:

1. First, arrange the digits of the given number in ascending order.
2. Next, arrange the same digits in descending order.
3. Find the difference between the two arranged numbers. Use this as the next
number in the sequence.

The sequence will eventually repeat at 0 (if all digits are the same) or, after a small
number of iterations, a short sequence common for all numbers of the same number
of digits. For 3- and 4-digit numbers, these are the single numbers 495 and 6174.

Example
For the 3-digit number 252, the sequence generated is 225, 297, 693, 594, 495, 495,
as shown below.

n(0) = 252
n(1) = 522 225 = 297
n(2) = 972 279 = 693
n(3) = 963 369 = 594
n(4) = 954 459 = 495
n(5) = 954 459 = 495

For the 4-digit number 3087, the sequence generated is 3087, 8352, 6174, 6174,
as shown below.

n(0) = 3087
n(1) = 8730 0378 = 8352
n(2) = 8532 2358 = 6174
n(3) = 7641 1467 = 6174

Problem
Write a program that will generate the described sequence for any given 4-digit
number.

Input
The program shall accept a 4-digit integer and use this as the initial number.

Output
The program shall list the sequence generated until it reaches 0 or 6174.

Input Validation
None.

Sample Test Runs
Enter the first 4-digit number: 5555
0
Enter the first 4-digit number: 3087
8352
6174
Enter the first 4-digit number: 5500
5445
1089
9621
8352
6174
Enter the first 4-digit number: 1025
5085
7992
7173
6354
3087
8352
6174

You might also like