-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path004-narcissistic.c
More file actions
97 lines (78 loc) · 1.73 KB
/
004-narcissistic.c
File metadata and controls
97 lines (78 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <stdio.h>
#include <stdint.h>
void print_narcissistic(uint32_t start, uint32_t end);
uint8_t num_length(uint32_t number);
uint32_t power(uint8_t base, uint8_t exp);
int main()
{
uint32_t start, end;
while (1)
{
fputs("Enter the left bound: ", stdout);
scanf("%u", &start);
fputs("Enter the right bound: ", stdout);
scanf("%u", &end);
print_narcissistic(start, end);
}
}
void print_narcissistic(uint32_t start, uint32_t end)
{
uint64_t sum;
uint8_t slen, elen;
uint32_t pow10, i, tmp;
printf("Narcissistic numbers between %u and %u: ", start, end);
sum = 0;
slen = num_length(start);
elen = num_length(end);
if (slen != elen)
{
pow10 = power(10, slen);
do
{
for (i = start; i < pow10; i++)
{
tmp = i;
sum = 0;
while (tmp)
{
sum += power(tmp % 10, slen);
tmp /= 10;
}
if (sum == i)
printf("%u ", i);
}
start = pow10;
slen++;
pow10 *= 10;
} while (slen != elen);
}
for (i = start; i <= end; i++)
{
tmp = i;
sum = 0;
while (tmp)
{
sum += power(tmp % 10, slen);
tmp /= 10;
}
if (sum == i)
printf("%u ", i);
}
putchar('\n');
}
uint8_t num_length(uint32_t number)
{
uint8_t len;
len = 1;
while (number /= 10)
len++;
return len;
}
uint32_t power(uint8_t base, uint8_t exp)
{
uint32_t res;
res = base;
while (--exp)
res *= base;
return res;
}