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

Function harshad_numbers_in_base

maths/special_numbers/harshad_numbers.py:89–126  ·  view source on GitHub ↗

Finds all Harshad numbers smaller than num in base 'base'. Where 'base' ranges from 2 to 36. Examples: >>> harshad_numbers_in_base(15, 2) ['1', '10', '100', '110', '1000', '1010', '1100'] >>> harshad_numbers_in_base(12, 34) ['1', '2', '3', '4', '5', '6', '7', '8', '9',

(limit: int, base: int)

Source from the content-addressed store, hash-verified

87
88
89def harshad_numbers_in_base(limit: int, base: int) -> list[str]:
90 """
91 Finds all Harshad numbers smaller than num in base 'base'.
92 Where 'base' ranges from 2 to 36.
93
94 Examples:
95 >>> harshad_numbers_in_base(15, 2)
96 ['1', '10', '100', '110', '1000', '1010', '1100']
97 >>> harshad_numbers_in_base(12, 34)
98 ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B']
99 >>> harshad_numbers_in_base(12, 4)
100 ['1', '2', '3', '10', '12', '20', '21']
101 >>> # bases below 2 and beyond 36 will error
102 >>> harshad_numbers_in_base(234, 37)
103 Traceback (most recent call last):
104 ...
105 ValueError: 'base' must be between 2 and 36 inclusive
106 >>> harshad_numbers_in_base(234, 1)
107 Traceback (most recent call last):
108 ...
109 ValueError: 'base' must be between 2 and 36 inclusive
110 >>> harshad_numbers_in_base(-12, 6)
111 []
112 """
113
114 if base < 2 or base > 36:
115 raise ValueError("'base' must be between 2 and 36 inclusive")
116
117 if limit < 0:
118 return []
119
120 numbers = [
121 int_to_base(i, base)
122 for i in range(1, limit)
123 if i % int(sum_of_digits(i, base), base) == 0
124 ]
125
126 return numbers
127
128
129def is_harshad_number_in_base(num: int, base: int) -> bool:

Callers

nothing calls this directly

Calls 2

int_to_baseFunction · 0.85
sum_of_digitsFunction · 0.70

Tested by

no test coverage detected