The number of Harshad is an integer divisible by the sum of its digits. For example 12 (= 3 * 4), 18, 20, 21 ... are such numbers. Write a function that, given an integer, determines whether it is a Harshad number or not.
Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include<conio.h>
int harshad(int n)
{
int s=0;
int m=n;
while (m>0)
{
s=s+m%10;
m=m/10;
}
if (n%s==0)
return s;
else
return -1;
}
void main()
{
int n,s;
for (n=1;n<200;n++)
{
s=harshad(n);
if (s!=-1)
printf("%d(%d)\t",n,s);
}
printf("\n");
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Add into a table based on coalesced hash without separated zones