-
Notifications
You must be signed in to change notification settings - Fork 0
/
The sum of digits of the number
41 lines (34 loc) · 1.35 KB
/
The sum of digits of the number
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#Produced by/Realizat de Casiu George Valentin
"""
Write a recursive function for calculate the sum of the digits of a natural number.
Să se scrie o funcţie pentru a calcula suma cifrelor unui număr natural.
"""
def citirenat(text):# natural number reading/citire numar natural
n=''
while not(n.isdecimal()): # if n is not decimal/daca n nu e zecimal
n = input(text)
n = n.strip(' +')# remove spaces and '+' from the beginning and end of number/elimina spatiile libere si '+' de la inceputul si sfarsitul numarului
return int(n)
def sumr(n):
if n==0: return 0
else: return n%10+sumr(n//10)
#The main program/ Programul principal
n=citirenat("Enter the number/Introduceti numarul:")
print("The sum of digits of the number is/Suma cifrelor numarului este:", sumr(n))
"""
#version 2/varianta 2
n=citirenat("Enter the number/Introduceti numarul:")
s=0
for i in range(len(str(n))):
s+=int(str(n)[i])
print("The sum of digits of the number is/Suma cifrelor numarului este:", s)
"""
"""
#version 3/varianta 3
n=citirenat("Enter the number/Introduceti numarul:")
s= 0
while n != 0:#calculate how may characters have number. We can change with n=len(str(m))/calculam cate caractere are numarul. Se poate inlocuii cu nr=len(str(m))
s += n%10
n //= 10
print("The sum of digits of the number is/Suma cifrelor numarului este:", s)
"""