FOR FREE YEAR SOLVED

Niven or Harshad number in a given range

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, the ranges are taken as input. For each number between these ranges, 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 and it is displayed as the output.

Algorithm

INPUT: The ranges
OUTPUT: The niven numbers between this range
PROCESS:
Step 1: [Taking the input]
	Read m, n [the ranges]
Step 2: [Finding the niven number]
	For k=m to n repeat
Set d<-0
		Set tmp<-k
		[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 k mod d=0 then
			Print k
		[End of ‘if’]	
	[End of ‘for’ loop]
Step 3: Stop.

Code

Time Complexity:

For(k=m;k<=n;k++)---------------------------------O(p)

                {              tmp=k;

                                D=0;

                                //adding the digits of the number

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

                                {                

                                                d=d+(tmp%10);

                                                tmp=tmp/10;         }              

                                //checking for niven number

                                If(k%d==0)-----------------------------O(1)

                                                Printf("%d ",k);     }

The time complexity of this program is O(p*n) where ‘p’ is the number between the range and ‘n’ is the number of digits of each number.

 

Space Complexity:

The space complexity of this program O(1) as it requires a constant number of spaces for any input.