4. Working with digits of a number (div and mod)
Integer division and remainder after division
Div
The div
operation is an integer division, where the result is a number without fractional part.
The div
operation calculates the integer part of the result of dividing integers (partial quotient ). For example:
10 div 2 = 5 22 div 7 = 3 65 div 10 = 6 --- N div K
N
div K
shows how many times K
«fits inside» N
.
Examples:
Example 1.How many Kilobytes are in x
bytes?
Answer: x div 1024
Example 2.
x
is a time in seconds
How many seconds have passed since the last minute?
Answer: x mod 60
Mod
The mod
operation calculates the remainder after dividing two integers. In this case, if the numbers are evenly divisible, the remainder is zero. Example:
10 mod 2 = 0 22 mod 7 = 1 65 mod 10 = 5 --- N mod K
N
mod K
shows the «remainder of N» after the maximum number of K
is «thrown» out of N
.Examples
Example 3.x mod 2 = 0 ⟹ x – even number x mod 2 <> 0 ⟹ x – odd number
Example 4.
var x := 1234; var LastDigit := x mod 10; // 4 var NumWithoutLastDigit := x div 10; // 123
Example 5.
// x is a 3-digit number. What is the second digit? // Answer: var x := ReadInteger('Enter x:'); // 456 x := x div 10; // 45 Print(x mod 10); // 5
Bitwise number operation
By parsing any integer N
into two components — the quotient d
and remainder m
, using the same divisor K
and operations div
and mod
, you will then easily restore this number by the formula:
If we have 10: 10 div 2 = 5 10 mod 2 = 0 ↓ 5 * 2 + 0 = 10
Examples:
10 div 2 = 5; 10 mod 2 = 0 => 5*2 + 0 = 10 22 div 7 = 3; 22 mod 7 = 1 => 3*7 + 1 = 22 65 div 10 = 6; 65 mod 10 = 5 => 6*10 + 5 = 65
Standard Form Of A Number
Any number can be disassembled into digits using powers of 10 and specified operations. This rule is called the standard form of a number:
Therefore, to make a certain number a hundred, you need to multiply it by 100 (as we have for digit 1
we have 1 * 100
= 100
).
- It can be seen that:
- to get hundred (first digit) of three-digit number, you need to calculate the quotient after dividing that number by 100 (number div 100, e.g.
123 div 100 = 1
) - to get ten (second digit), you need to calculate the remainder after dividing that number by 100, and then — the quotient of dividing the result by 10 (1. number mod 100:
123 mod 100 = 23;
2.23 div 10 = 2
) (also there is another way) - to get unit number (third digit), you need to calculate remainder after dividing this number by 10 (number mod 10:
123 mod 10 = 3
).
For numbers with a different bit width, these algorithms can be changed.