The need to use the operation of calculating the remainder of the division is visible when working with digits of a number.
Let's analyze the following task:
A three-digit number is given. Display all the digits of this number, starting with units, and get a new number formed by a permutation of units and hundreds
The most difficult question that arises for beginners is how to get and get its numbers from a number.
In fact, everything is solved quite simply, if you recall the mathematics. And mathematics tells us that any number can be decomposed into the sum of the bit terms.
For example: 365 = 3 * 100 + 6 * 10 + 5 * 1.
We see that each digit is a factor in the corresponding digit category.
We show how to get each digit of a number into a separate variable, using the example of dividing a column by 10. (we take the number 10, because we have a decimal number system and, accordingly, bit terms, we have 1, 10, 100, etc. )
After analyzing the figure, you can see that
e = n % 10
# operation n % 10 - computes the last digit of the number n (i.e., the units of a number) 365 % 10 = 5
d = n // 10 % 10
# operation n // 10 - reduces the number by 10 times, that is, it discards the last digit from the number (365 // 10 = 36),
# Now we can calculate the number of tens by applying the familiar operation to the result - calculate the remainder of the division by the number 10, 36 % 10 = 6
s = n // 100
# to get hundreds, it’s enough to discard two digits from the number on the right, that is, double by 10 (n // 10 // 10 или то же самое, что n // 100) 365 // 100 = 3
Having the digits of numbers stored in variables, we can compose any other number from them, multiplying the required digit by the corresponding digit factors (by 1, 10, 100, etc.):
for example, the line below will get a new number from the original number n, which has hundreds and ones rearranged:
1) the old number of units (stored in variable e) is multiplied by 100
2) the old number of tens (stored in the variable d) is multiplied by 10
3) we can multiply the old number of hundreds simply by 1, or simply take the value stored in the variable s
Then the values from points 1, 2 and 3 are simply added and we get a new number:
n1 = e*100 + d*10 + s;
The whole program will look like this:
n = int(input())
e = n % 10
d = n // 10 % 10
s = n // 100
print(e, d, s, e*100 + d*10 + s)