Skip to content

Commit 193947f

Browse files
Merge pull request kennyledet#480 from jb1717/master
Harshad number C implementation
2 parents e16244b + 0db8a34 commit 193947f

3 files changed

Lines changed: 75 additions & 0 deletions

File tree

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*
2+
** A harshad number is an integer that is divisible by the sum of its digits
3+
** Here we only use the base 10
4+
** For more information : https://en.wikipedia.org/wiki/Harshad_number
5+
*/
6+
7+
static int sumDigit(int n)
8+
{
9+
int sum = 0;
10+
11+
while (n)
12+
{
13+
sum += n % 10;
14+
n /= 10;
15+
}
16+
return (sum);
17+
}
18+
19+
/*
20+
** Return if the number is Harshad or not
21+
*/
22+
int isHarshad(int n)
23+
{
24+
int sum = sumDigit(n);
25+
26+
if (!sum)
27+
return (0);
28+
return (n % sum == 0);
29+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
#ifndef HARSHAD_NUMBER
2+
# define HARSHAD_NUMBER
3+
4+
int isHarshad(int n);
5+
6+
#endif
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#include <stdio.h>
2+
#include <assert.h>
3+
#include "10_Harshad_Number.h"
4+
5+
/*
6+
** This test try all number between 1 and 200 and print only harshad numbers
7+
*/
8+
int main(void)
9+
{
10+
int pretty = 0;
11+
int idx = 0;
12+
int sample[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
13+
12, 18, 20, 21, 24, 27, 30, 36,
14+
40, 42, 45, 48, 50, 54, 60, 63,
15+
70, 72, 80, 81, 84, 90, 100, 102,
16+
108, 110, 111, 112, 114, 117, 120,
17+
126, 132, 133, 135, 140, 144, 150,
18+
152,153, 156, 162, 171, 180, 190,
19+
192, 195, 198, 200};
20+
21+
printf("Display all Harshad numbers between 1 and 200\n\n");
22+
23+
for (int i = 0; i < 201; ++i)
24+
{
25+
if (isHarshad(i))
26+
{
27+
// if a number is consider Harshad but not in the sample
28+
assert(sample[idx++] == i);
29+
30+
printf("%d", i);
31+
pretty++;
32+
if (pretty % 5 == 0)
33+
printf("\n");
34+
else
35+
printf("\t");
36+
}
37+
}
38+
printf("\n\n=== END ===\n\n");
39+
return (0);
40+
}

0 commit comments

Comments
 (0)