Answer the question
In order to leave comments, you need to log in
Could you please explain how this program (cycles) python works?
Hello. There is a Gaussian method, how to calculate the sum of all numbers, for example, from 1 to 9, it will be 45, from 1 to 100 it will be 5050. This is understandable. But there is such a task, how to calculate the sum of all digits in a number, i.e. the number 12 will be like 1 + 2, i.e. for example 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 (1 +0)+11(1+1) = 48, i.e., numbers in which there are more than one digits are divided into digits and thus summed up. Here is a program not mine, but I'm confused how it does it. Help, if anyone understands, describe in detail how cycles work here!
i = 0
x = 0
while i <= 12:
j = 0
for j in str (i):
x += int(j)
i += 1
print(x)
Answer the question
In order to leave comments, you need to log in
The program is a sample of bad code, so it's better not to write it, it would be much better to do something like this:
def compute_digits_sum(number):
digits_sum = 0
while number:
digits_sum += number % 10
number = number // 10
return digits_sum
def compute_progression_digits_sum(number):
return sum(compute_digits_sum(i) for i in range(number + 1))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question