# Algorithm and Flowchart to check whether a given number is Niven number or not

[555 views]

### What are Niven Numbers?

A number given in any base is said to be a Niven number if it is divisible by the sum of its digits in that same base. In simple terms, a Niven number is a number that is divisible by the sum of its digits. Niven numbers are also known as Harshad numbers. An n-harshad number is an integer number divisible by the sum of its digit in base n. For example: 2, 3, 18, 45, 63, etc. are Niven numbers.

Let us consider the number 120:
Sum of the digits = 1+2+0 = 3 120 / 3 = 40 120 is divisible by 3. Therefore, 120 is a Niven number.

Let us consider the number 145:
Sum of the digits = 1+4+5 = 10 145 / 10 = 14.5 145 is not divisible by 10. Therefore, 145 is not a Niven number.

In this article, we will learn about the algorithm and flowchart to check whether a given number is Niven or Harshad number or not.

## Algorithm to check whether a given number is Niven number or not:

Step 1: Start Step 2: Read the number from the user, say n Step 3: Create a copy of the number, temp = n Step 4: Initialize the sum of the digits of the number, sum = 0 Step 5. Repeat WHILE n ≠ 0: 5.1: Extract the last digit by: d = n % 10 5.2: Calculate sum by: sum = sum + d 5.3: Remove the last digit from the number: n = n / 10 Step 6. If temp % sum = 0, then: 6.1: Print “Niven/Harshad number” Step 7. Else: 7.1: Print “Not Niven/Harshad number” Step 8: Stop

## Explanation:

In this problem, we need to check whether a give number is a Niven number or not. To check this, we need to calculate the sum of the digits of the given number and check whether the number is divisible by that sum or not. If the number is divisible by that sum, it is a Niven number.

The algorithm starts off by taking the number to checked as user input, then the value is stored in a variable, say ‘n’. We create a copy of this number and store it in a variable say ‘temp’. This variable is required for doing the divisibility checking later. We now have to find out the sum of the digits. To do so, a while loop is started which runs until n is not equal to zero. We then extract the last digit of the number by performing: d = n % 10. After that, the extracted digit is added to the sum of the digits, ‘sum’ with the help of the statement: sum = sum + d. This loop continues iterating until no digits are left in n, that is, n is equal to zero.

Once this loop completes its execution, we get the sum of digits in ‘sum’. Now, we check whether temp is divisible by sum or not. If this checking returns true, we display “Niven number”, else, we display “Not Niven number”.

Note: Here ‘%’ is the modulus operator which returns the remainder value after division.

Let us consider an example:
Let n = 180
sum = 1+8+0 = 9
180 % 9 = 0
Hence, 180 is a Niven number.

## Flowchart to check whether a given number is Niven number or not : ##### Play 2048 Game Online and Relax. 