MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / sum_of_digits

Function sum_of_digits

maths/special_numbers/harshad_numbers.py:56–86  ·  view source on GitHub ↗

Calculate the sum of digit values in a positive integer converted to the given 'base'. Where 'base' ranges from 2 to 36. Examples: >>> sum_of_digits(103, 12) '13' >>> sum_of_digits(1275, 4) '30' >>> sum_of_digits(6645, 2) '1001' >>> # bases below 2 and b

(num: int, base: int)

Source from the content-addressed store, hash-verified

54
55
56def sum_of_digits(num: int, base: int) -> str:
57 """
58 Calculate the sum of digit values in a positive integer
59 converted to the given 'base'.
60 Where 'base' ranges from 2 to 36.
61
62 Examples:
63 >>> sum_of_digits(103, 12)
64 '13'
65 >>> sum_of_digits(1275, 4)
66 '30'
67 >>> sum_of_digits(6645, 2)
68 '1001'
69 >>> # bases below 2 and beyond 36 will error
70 >>> sum_of_digits(543, 1)
71 Traceback (most recent call last):
72 ...
73 ValueError: 'base' must be between 2 and 36 inclusive
74 >>> sum_of_digits(543, 37)
75 Traceback (most recent call last):
76 ...
77 ValueError: 'base' must be between 2 and 36 inclusive
78 """
79
80 if base < 2 or base > 36:
81 raise ValueError("'base' must be between 2 and 36 inclusive")
82
83 num_str = int_to_base(num, base)
84 res = sum(int(char, base) for char in num_str)
85 res_str = int_to_base(res, base)
86 return res_str
87
88
89def harshad_numbers_in_base(limit: int, base: int) -> list[str]:

Callers 2

harshad_numbers_in_baseFunction · 0.70

Calls 1

int_to_baseFunction · 0.85

Tested by

no test coverage detected