Programmers Arena: NIVEN / HARSHAD Numbers in Python

NIVEN / HARSHAD Numbers in Python

To all of you coding enthusiasts there, I've been working on some special series of mathematics, namely, Harshad/Niven Numbers, The Collatz Conjecture, Self Numbers, Kaprekar Numbers, Smith Numbers, Happy and Unhappy Numbers.
I'll be posting the codes for all of them and many more.
Let's start with The Niven/Harshad Numbers.
For those of you who don't know what HARSHAD/NIVEN NUMBERS are refer to the link below:

http://en.wikipedia.org/wiki/Harshad_number

Before you start, we'd be doing the series only in base 10 numbers, but you may write scripts for other bases as well and maybe mail it to me, or comment the link? :)

To start with, we first need to design a script that would separate the digits of a given number, what we can easily do is,
let 'i' be the number you want to verify if its a Niven number or not, and 'a','b','c' are the variables containing the values of the digits,

i=input("Input Number:")
a=i/100
b=i/10-a*10
c=i-b*10-a*100

Now, what you'd want to check is whether the number 'i' is completely divisible by the sum of those digits it consists of.
Consider a variable 'z',

z=a+b+c

if i/z==i/float(z):
        print i," ---> Niven/Harshad number"
       
    elif i/z!=i/float(z):
        print i," ---> not Niven/Harshad number"
       
If you divide the number directly by its sum without mentioning it to be a float point number, it would always give you a whole number, which is not valid for our script, thus using this error of mine I created a way to verify whether the division gave us the right output or not.
Use lists if you want to save the values of the Niven Numbers till the time your program is running.
In a whole your program may look something like this,

l1=[]
l2=[]
for i in range (1,1000):
   a=i/100
   b=i/10-a*10
   c=i-b*10-a*100
   z=a+b+c
   if i/z==i/float(z):
       print i," ---> Niven/Harshad number"
       l1.append(i)
   elif i/z!=i/float(z):
       print i," ---> not Niven/Harshad number"
       l2.append(i)

If you want to further increase the range of the loop you will have to use some more variables to contain the digits of the higher numbers.
Thanks for reading this post, do remember to subscribe, like, share and comment your views!

No comments:

Post a Comment

Copyright © Programmers Arena