📅  最后修改于: 2023-12-03 14:41:41.473000             🧑  作者: Mango
Harshad Number, also known as Niven Number, is a positive integer that is divisible by the sum of its digits. For example, 18 is a Harshad Number because 1 + 8 = 9 and 18 is divisible by 9 (18/9 = 2).
Here is an implementation of checking if a number is a Harshad Number in Python:
def is_harshad_number(n):
"""Returns True if n is a Harshad Number, False otherwise."""
sum_of_digits = sum(int(digit) for digit in str(n))
return n % sum_of_digits == 0
# Example usage
print(is_harshad_number(18)) # True
print(is_harshad_number(19)) # False
In the above implementation, we first convert the number n
to a string so that we can iterate over its digits. We compute the sum of the digits using a generator expression, and then check if n
is divisible by the sum of its digits.
A Harshad (Niven) Sequence is a sequence of numbers in which each number is a Harshad Number, except for the first number which can be any positive integer.
Here is an implementation of generating the first n
numbers in a Harshad (Niven) Sequence in Python:
def harshad_sequence(n):
"""Generates the first n numbers in the Harshad (Niven) Sequence."""
count = 0
num = 1
while count < n:
if is_harshad_number(num):
yield num
count += 1
num += 1
# Example usage
for num in harshad_sequence(10):
print(num)
This will print the first 10 numbers in the Harshad (Niven) Sequence.
Harshad (Niven) Numbers are a fascinating subject in mathematics and have practical applications in areas such as digital root analysis. With the implementation and generation of Harshad (Niven) Numbers, programmers can now leverage its properties and capabilities in various projects.