FOR FREE MATERIALS

Niven Number or Harshad Number

Back to Programming

Description

A number is said to be a niven number or harshad number if the number is divisible by the sum of the digits of the number.

 

For example, if the number is 18, the sum of the digits is 1+8=9 and the number ’18’ is divisible by 9. Therefore, 18 is a niven number.

If the number is 16, the sum of the digits is 1+6=7 and the number ‘16’ is not divisible by 7. Therefore, 16 is not a niven number.

 

For this program, a number is taken as input. Then the sum of the digits is calculated. If the number is divisible by the sum of the digits, then the number is a niven number or not.

Algorithm

INPUT: A number
OUTPUT: Whether a number is a niven number or not.
PROCESS:
Step 1: [Taking the input]
	Read n [the number to check]
Step 2: [Checking for niven number]
	Set d<-0
	Set tmp<-n
	[Adding the digits of the number]
	While tmp>0 repeat
		Set d<-d+(tmp mod 10)
		Set tmp<-tmp/10
	[End of ‘while’ loop]
	[Checking for niven number]
	If n mod d=0 then
		Print "The number is a niven number"
	Else
		Print "The number is not a niven number"
	[End of ‘if-else’]
Step 3: Stop.

Code

Time Complexity:

while(tmp>0) --------------------------------------O(n) [‘n’ is the number of digits]

                {               d=d+(tmp%10);

                                tmp=tmp/10;  }

                //checking for niven number

                if(n%d==0)------------------------------------------O(1)

                                printf("The number is a niven number");

                else---------------------------------------------------O(1)

                                printf("The number is not a niven number");

 

The time complexity to check whether a number is a niven number or not is O(n) where ‘n’ is the number of digits of the input number.

 

Space Complexity: 

The space complexity of this program is O(1) as it requires a constant memory space to execute for any given input.