The sum of the digits of a random three-digit number
The program generates a random three-digit number and calculates the sum of its digits.
In this case, the problem can be solved using a linear algorithm, since the amount of digits of a number is known and this amount is small. However, similar tasks, especially when the amount of digits are unknown, are solved using cycles.
from random import randint
n = randint(100, 999)
print(n)
a = n // 100
b = (n // 10) % 10
c = n % 10
print(a+b+c)
With comments:
from random import randint
n = randint(100, 999)
print(n)
# The first digit (the most significant digit)
# is extracted by dividing by 100.
a = n // 100
# The last digit is removed by dividing by 10.
# The first two digits remain.
# By finding the remainder by dividing by 10,
# we get the last digit of this two-digit number,
# which is also the middle digit of the original number.
b = (n // 10) % 10
# The last digit (the lowest significant digit)
# is extracted by finding the remainder
# after dividing by 10.
c = n % 10
print(a+b+c)
In this method of solving, a three-digit number is converted into a string consisting of three characters. For this, the str
function is used.
Each character-digit is extracted from the string: s[0]
, s[1]
, s[2]
. Each of them is converted back to a number using the int
function.
from random import randint
n = randint(100, 999)
print(n)
s = str(n)
a = int(s[0])
b = int(s[1])
c = int(s[2])
print(a + b + c)
The divmod
function performs an integer division of the first argument by the second and returns the quotient and remainder.
from random import randint
n = randint(100, 999)
print(n)
n, c = divmod(n, 10)
a, b = divmod(n, 10)
print(a + b + c)
Example of program execution: