Number+Theory+for+Newbies

Given any positive integer, if we permute its digits, the difference between the number we get

and the given number will always be divisible by 9. For example, if the given number is 123,

we may rearrange the digits to get 321. The difference = 321 - 123 = 198, which is a multiple

of 9 (198 = 9 × 22).

We can prove this fact fairly easily, but since we are not having a maths contest, we instead

try to illustrate this fact with the help of a computer program.

Input and Output
Each line of input gives a positive integer n (£ 2000000000). You are to find two integers a

and b formed by rearranging the digits of n, such that a-b is maximum. a and b should NOT

have leading zeros. You should then show that a-b is a multiple of 9, by expressing it as 9 ×

k, where k is an integer. See the sample output for the correct output format.

Sample Input
123

2468

Sample Output
321 - 123 = 198 = 9 * 22

8642 - 2468 = 6174 = 9 * 686

Source Code code format="java5" public class NumberTheoryForNewbies { public static void main(String[] args) { int input = 123; System.out.println(output(input));

input = 2468; System.out.println(output(input)); }

public static String output(int a) {

// 입력 숫자를 문자열로 바꾼다. String forward = Integer.toString(a);

// 문자열을 뒤집는다. String backward = new StringBuffer(forward).reverse.toString;

// 뒤집힌 문자열을 숫자로 바꾼다. int b = Integer.parseInt(backward);

int remainder;   // 두 수의 차이 String output;   // 출력식

// 큰 수에서 작은 수를 뺀다. if(a > b) { remainder = a - b;           output = forward + " - " + backward; } else { remainder = b - a;           output = backward + " - " + forward; }

// 형식에 맞게 출력한다. return output + " = " + remainder + " = 9 * " + remainder / 9; } } code

Comment