Skip to content
Educora
IntermediateGrades 8–925 min32 / 59

Working with numbers: digits, divisors and primes

Split a number into digits with `n % 10` and `n // 10`; find the sum, product, count and reverse of the digits; count divisors; test primes and perfect squares; compute the GCD with Euclid's algorithm. Ready templates for the DİM tasks.

Check yourself
In this lesson you will learn
  • take a number apart with n % 10 and n // 10 and find the sum, product, count and reverse of its digits
  • count and add up divisors and test whether a number is prime or a perfect square
  • compute the GCD and LCM with Euclid's algorithm and sums such as 1 + 1/2 + … + 1/n with a loop
  • check every number of an interval with nested loops and recognise the ready templates in DİM tasks

Has a bank card number been typed correctly? The algorithm that checks it takes the number apart digit by digit, adds the digits up and looks at a remainder. Every DİM informatics paper has 3–4 tasks on the topic «loops and working with numbers», and in three of the four 2025–2026 papers one of the written programs came from this topic too. The good news: almost all of these tasks are built from a few ready templates — the digit loop, the divisor loop and Euclid's algorithm. This lesson continues «Loops: for, while, step, break, continue and nested loops».

Taking digits apart: n % 10 and n // 10

In the decimal system the last digit of a number is the remainder of dividing it by 10, and integer division by 10 drops that digit: 5682 % 10 = 2, 5682 // 10 = 568. Repeat these two operations in a loop and you get the digits one by one from right to left; when the number becomes 0, the digits have run out.

d = n % 10 n = n // 10
where:
  • dthe last digit (0…9)
  • %the remainder of division
  • //integer division: the fractional part is dropped and the number loses one digit

The two key commands of the digit loop. The loop runs with the condition while n > 0:.

n // pow(10, k) % 10 n % pow(10, k) n // pow(10, k)
where:
  • n // pow(10, k) % 10the k-th digit from the right (k = 0 — units, 1 — tens, 2 — hundreds)
  • n % pow(10, k)the number formed by the last k digits
  • n // pow(10, k)what is left after dropping the last k digits

Any digit can be taken without a loop: 5682 // 100 % 10 = 6, 5682 % 100 = 82, 5682 // 1000 = 5.

Example 1. Picking digits

Compute: 1) 7049 % 10 and 7049 // 10; 2) the tens digit and the hundreds digit of 7049; 3) 30 % 10 and 30 // 10.

Show solution
1) 7049 = 704 · 10 + 9, so 7049 % 10 = 9 and 7049 // 10 = 704.
2) Tens: 7049 // 10 % 10 = 704 % 10 = 4. Hundreds: 7049 // 100 % 10 = 70 % 10 = 0.
3) 30 % 10 = 0, 30 // 10 = 3. A last digit can be 0 — the digit loop counts it too.
  1. 1
    Keep a copy

    The loop will change n until it becomes 0. If you need the original number later, first write m = n.

  2. 2
    Starting values

    sum s = 0, product p = 1, count c = 0, reverse r = 0.

  3. 3
    Loop condition

    while n > 0: — as long as digits are left.

  4. 4
    Take the digit and use it

    d = n % 10, then s = s + d, p = p * d, c = c + 1, r = r * 10 + d, or a condition such as if d % 2 == 0:.

  5. 5
    Drop the digit

    n = n // 10. Forget this line and the loop never ends.

Python
n = 5682
s = 0
p = 1
c = 0
r = 0
while n > 0:
    d = n % 10
    s = s + d
    p = p * d
    c = c + 1
    r = r * 10 + d
    n = n // 10
print(s, p, c, r)
▸ Expected output
21 480 4 2865
Sum, product, count and reverse of the digits in one loop. In an exam program the first line is n = int(input()); here the value is written into the variable so that the program runs in the browser.
Python
x = 3704
k = 0
m = x
while x > 0:
    if x % 10 % 2 == 0:
        k = k + 1
    x = x // 10
print(m * 10 + k)
▸ Expected output
37042
The program of Example 2. Work out the result yourself first, then run the program to check.
Example 2. A DİM-style task: the output of a program

In the exam the program above starts with x = int(input()), and 3704 is typed on the keyboard. Determine the output of the program.
A) 37041 B) 3704 C) 37042 D) 24073 E) 37043

Show solution
Trace table (x → last digit, even?, k):
3704 → 4, even, k = 1
370 → 0, even, k = 2
37 → 7, odd, k = 2
3 → 3, odd, k = 2
x = 0 — the loop ends. m kept the original number: m · 10 + k = 37040 + 2 = 37042.
Answer: C. Trap: 0 is an even digit too; whoever forgets it picks 37041.

Reverse numbers, palindromes and «all digits odd»

To build the reverse, at every step multiply the result so far by 10 and add the new digit: the earlier digits move one place to the left. A number equal to its reverse is a palindrome: 121, 4554, 7.

r = r * 10 + n % 10
where:
  • rthe reversed number; at the start r = 0
  • n % 10the next last digit

Reverse: for 5682, r = 2, 28, 286, 2865. Palindrome test: after the loop, r == m (m is the copy of the original number).

a * pow(10, c) + n n * 10 + a
where:
  • cthe number of digits of n (the counter of the digit loop)
  • athe digit being added

Writing the digit a in front of the number and at its end.

Example 3. Reversing and adding digits

1) Find the reverse of 1230; is 1230 a palindrome? 2) Is 4554 a palindrome? 3) Write the digit 7 in front of 309 and at its end.

Show solution
1) r: 0 → 3 → 32 → 321. The reverse is 321 (0321 is not written); 321 ≠ 1230 — not a palindrome.
2) r: 4 → 45 → 455 → 4554 = n, so it is a palindrome.
3) 309 has c = 3 digits: 7 · 10³ + 309 = 7309; at the end: 309 · 10 + 7 = 3097.

«Are all the digits odd?» can be answered in two ways: count the odd digits and compare with the total number of digits, or use a flag variable: first t = 1 («all odd so far»), and t = 0 as soon as an even digit appears. In the program below the outer loop walks through the numbers and the inner loop through their digits.

Python
for n in [357, 48, 1991, 7, 5031]:
    m = n
    t = 1
    while m > 0:
        if m % 10 % 2 == 0:
            t = 0
        m = m // 10
    if t == 1:
        print(n)
▸ Expected output
357
1991
7
5031 is not printed: 0 is an even digit. In a written task the numbers are read one by one with int(input()).

Divisors, primes and perfect squares

Definition
Divisor

If n divides by i with no remainder, i is a divisor of n: n % i == 0. Every natural number greater than 1 has at least two divisors: 1 and itself.

Definition
Prime number

A natural number with exactly two natural divisors (1 and itself): 2, 3, 5, 7, 11, 13, … A number with more than two divisors is composite; 1 is neither prime nor composite.

Definition
Perfect square

A number that is the square of a natural number: 1, 4, 9, 16, 25, 36, …

n % i == 0, i = 1, 2, …, n
where:
  • ithe candidate divisor being checked
  • c == 2if the number of divisors is 2, n is prime

The divisor loop: for i in range(1, n + 1): with if n % i == 0: inside.

Python
n = 60
c = 0
s = 0
t = 0
for i in range(1, n + 1):
    if n % i == 0:
        print(i, end=' ')
        c = c + 1
        s = s + i
        if i % 2 == 1:
            t = t + i
print()
print(c, s, t)
▸ Expected output
1 2 3 4 5 6 10 12 15 20 30 60 
12 168 24
The divisors of 60, how many there are (12), their sum (168) and the sum of the odd divisors (1 + 3 + 5 + 15 = 24). end=' ' prints the divisors on one line.
pow(a, 0.5) == int(pow(a, 0.5))
where:
  • pow(a, 0.5)the square root of a, a float (49 ** 0.5 → 7.0)
  • int(…)drops the fractional part

If the root is a whole number, a is a perfect square. DİM solutions also write a ** (1/2) — it is the same thing.

Example 4. Divisors, primality, squares

1) How many divisors does 36 have? 2) Is 97 prime? 3) Find the sum of the divisors of 28 other than 28 itself. 4) How many perfect squares are there in [30, 50]?

Show solution
1) 1, 2, 3, 4, 6, 9, 12, 18, 36 — 9 divisors. The count is odd because divisors come in pairs (1 · 36, 2 · 18, 3 · 12, 4 · 9) and 6 pairs with itself: 6 · 6 = 36.
2) It is enough to try 2 to 9 (10 · 10 = 100 > 97). None of them divides 97, so 97 has only two divisors — it is prime.
3) 1 + 2 + 4 + 7 + 14 = 28 — the sum equals the number itself (such numbers are called perfect numbers).
4) 36 and 49: 36 ** 0.5 → 6.0, 49 ** 0.5 → 7.0. Answer: 2.

Nested loops: checking every number of an interval

When a task asks about every number of an interval [a, b] rather than about one number, put the divisor (or digit) loop inside another loop: the outer loop walks through the numbers, the inner one through the divisors. The counter (c = 0) must be reset for every new number, so it is written inside the outer loop.

Python
a = 20
b = 40
k = 0
for n in range(a, b + 1):
    c = 0
    for i in range(1, n + 1):
        if n % i == 0:
            c = c + 1
    if c == 2:
        print(n, end=' ')
        k = k + 1
print()
print('count =', k)
▸ Expected output
23 29 31 37 
count = 4
The primes in [20, 40]. Move the line c = 0 above the outer loop and see what changes.
Example 5. How many times does the inner loop run?

In the program above, how many times in total is the check if n % i == 0 executed?

Show solution
For each n the inner loop takes i = 1, 2, …, n, so it runs n times. Total: 20 + 21 + … + 40, an arithmetic sequence of 21 terms: (20 + 40) · 21 / 2 = 630.
Answer: 630. With the √n rule the number of checks would drop sharply.

GCD, LCM and sums

The greatest common divisor (GCD) of two numbers can be found without checking every divisor, with Euclid's algorithm. It rests on one fact: the remainder of a divided by b is also divisible by gcd(a, b). So the pair (a, b) can be replaced with (b, a % b), and the numbers shrink fast.

gcd(a, b) = gcd(b, a % b), gcd(a, 0) = a
where:
  • a % bthe remainder of a divided by b
  • b = 0stop when the remainder is 0: the answer is a

Euclid's algorithm. Textbooks also give a subtraction version: subtract the smaller number from the larger until they are equal.

lcm(a, b) = a · b / gcd(a, b)lcm(a, b) = a · b / gcd(a, b)
where:
  • a · bthe product of the two numbers

The least common multiple follows at once from the GCD.

Python
a = 84
b = 36
p = a * b
while b != 0:
    r = a % b
    a = b
    b = r
print(a, p // a)
▸ Expected output
12 252
(84, 36) → (36, 12) → (12, 0): gcd = 12, lcm = 3024 / 12 = 252. Subtraction version: (84, 36) → (48, 36) → (12, 36) → (12, 24) → (12, 12).
Example 6. GCD and LCM

Find gcd(126, 84) and lcm(126, 84) with Euclid's algorithm. How many times does the loop run?

Show solution
(126, 84): 126 % 84 = 42 → (84, 42)
(84, 42): 84 % 42 = 0 → (42, 0) — stop.
gcd = 42, the loop ran 2 times. lcm = 126 · 84 / 42 = 10584 / 42 = 252.

Sums and products of sequences follow the same scheme: an accumulator (s = 0) or a multiplier (p = 1) and one term per step of the loop. Fractions use /, so the result is a float.

S = 1 + 1/2 + 1/3 + … + 1/n n! = 1 · 2 · 3 · … · nS = 1 + 1/2 + 1/3 + … + 1/n n! = 1 · 2 · 3 · … · n
where:
  • s = s + 1 / is = s + 1 / ithe loop template of the sum
  • p = p * ithe template of the factorial (at the start p = 1)

i is the loop variable: for i in range(1, n + 1):.

Python
n = 4
s = 0
p = 1
for i in range(1, n + 1):
    s = s + 1 / i
    p = p * i
print(round(s, 4), p)
▸ Expected output
2.0833 24
1 + 1/2 + 1/3 + 1/4 = 25/12 ≈ 2.0833 and 4! = 24. round(s, 4) rounds the result to 4 decimal places.
Example 7. An alternating sum

Build a loop that computes S = 1 − 1/2 + 1/3 − 1/4 and find S.

Show solution
Use a sign variable z: first z = 1, and at each step s = s + z / i and z = -z.
i = 1: s = 1
i = 2: s = 1 − 1/2 = 1/2
i = 3: s = 1/2 + 1/3 = 5/6
i = 4: s = 5/6 − 1/4 = 7/12 ≈ 0.5833.
The same idea in a flowchart is used in «Building flowcharts: the written tasks».
TaskTemplate
sum of the digitss = s + n % 10, n = n // 10
number of digitsc = c + 1; len(str(n))
reverse, palindromer = r * 10 + n % 10; r == m
number of divisorsif n % i == 0: c = c + 1
prime numberc == 2
perfect squarea ** 0.5 == int(a ** 0.5)
GCDr = a % b, a = b, b = r
the sum 1 + 1/2 + … + 1/ns = s + 1 / i
Ready templates. Turning them into complete programs is shown in «Writing programs: the written tasks».
Check yourself: fill in the gap
  1. 1.The last digit of a number: d = n 10
  2. 2.Reverse: r = r * + n % 10
  3. 3.A prime number has exactly divisors.
  4. 4.gcd(48, 18) =
  5. 5.The number of perfect squares from 1 to 100:
Exercise

Using a while loop, find the sum of the digits of n = 90517 and its reverse, and print them on one line separated by a space.

Exercise · Python
n = 90517
s = 0
r = 0
# digit loop here

print(s, r)
▸ Expected output
22 71509
Exercise

Print the numbers from 1 to 100 (inclusive) that have exactly 3 divisors, each on its own line. Then look at them: what do they have in common?

Exercise · Python
for n in range(1, 101):
    c = 0
    # count the divisors of n here

    if c == 3:
        print(n)
▸ Expected output
4
9
25
49

Key points

  • n % 10 gives the last digit and n // 10 drops it; the digit loop runs while n > 0:.
  • A sum starts at 0 and a product at 1; the reverse is built with r = r * 10 + d, and a palindrome equals its reverse.
  • i is a divisor of n ⇔ n % i == 0; a prime has exactly 2 divisors, and a prime test only needs i up to i * i <= n.
  • Perfect square: a ** 0.5 == int(a ** 0.5); GCD — Euclid's algorithm, LCM = a · b / GCD.
  • For every number of an interval the outer loop walks through the numbers and the inner loop through their divisors or digits; the counter is reset inside the outer loop.

Check yourself

12 questions. Every correct answer earns XP.

1 / 12
Which expression gives the last digit of n?