Dremendo Tag Line

Input a number and check if it is a Niven (Harshad) number or not using a function in Python

Function - Question 9

In this question, we will see how to input a number and check if it is a Niven (Harshad) number or not in Python programming using a function. To know more about function click on the function lesson.

Q9) Write a program in Python to input a number and check if it is a Niven (Harshad) number or not using a function. The function should return 1 if the numbers is a Niven number else return 0.

A Niven number is an integer number that is divisible by the sum of its digits.

Example: 18 is a Niven number because the sum of its digit is 9 and 18 is divisible by 9.

Program

def niven(num):
    s=0
    t=num
    while t>0:
        d=t%10
        s=s+d     # sum of the digits
        t=t//10

    if num%s==0:
        return 1

    return 0


# main program
n=int(input('Enter a number '))
if niven(n)==1:
    print('Niven Number')
else:
    print('Not Niven Number')

Output

Enter a number 18
Niven Number
video-poster