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

Function is_harshad_number_in_base

maths/special_numbers/harshad_numbers.py:129–160  ·  view source on GitHub ↗

Determines whether n in base 'base' is a harshad number. Where 'base' ranges from 2 to 36. Examples: >>> is_harshad_number_in_base(18, 10) True >>> is_harshad_number_in_base(21, 10) True >>> is_harshad_number_in_base(-21, 5) False >>> # bases below 2 and bey

(num: int, base: int)

Source from the content-addressed store, hash-verified

127
128
129def is_harshad_number_in_base(num: int, base: int) -> bool:
130 """
131 Determines whether n in base 'base' is a harshad number.
132 Where 'base' ranges from 2 to 36.
133
134 Examples:
135 >>> is_harshad_number_in_base(18, 10)
136 True
137 >>> is_harshad_number_in_base(21, 10)
138 True
139 >>> is_harshad_number_in_base(-21, 5)
140 False
141 >>> # bases below 2 and beyond 36 will error
142 >>> is_harshad_number_in_base(45, 37)
143 Traceback (most recent call last):
144 ...
145 ValueError: 'base' must be between 2 and 36 inclusive
146 >>> is_harshad_number_in_base(45, 1)
147 Traceback (most recent call last):
148 ...
149 ValueError: 'base' must be between 2 and 36 inclusive
150 """
151
152 if base < 2 or base > 36:
153 raise ValueError("'base' must be between 2 and 36 inclusive")
154
155 if num < 0:
156 return False
157
158 n = int_to_base(num, base)
159 d = sum_of_digits(num, base)
160 return int(n, base) % int(d, base) == 0
161
162
163if __name__ == "__main__":

Callers

nothing calls this directly

Calls 2

int_to_baseFunction · 0.85
sum_of_digitsFunction · 0.70

Tested by

no test coverage detected