aboutsummaryrefslogtreecommitdiff
path: root/challenge-007/paulo-custodio/c/ch-1.c
blob: 02cad54f5dc92a45ba63327938c4c0b2b3cf5aae (plain)
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
/*
Challenge 007

Challenge #1
Print all the niven numbers from 0 to 50 inclusive, each on their own line.
A niven number is a non-negative number that is divisible by the sum of its
digits.
*/

#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

bool is_niven(int n) {
    assert(n > 0);
    int sum = 0;
    int rem = n;
    while (rem > 0) {
        int digit = rem % 10;
        rem /= 10;
        sum += digit;
    }
    if (n % sum == 0)
        return true;
    else
        return false;
}

int main(int argc, char* argv[]) {
    int max = 50;
    if (argc == 2) max = atoi(argv[1]);
    if (max < 1) return EXIT_FAILURE;
    for (int n = 1; n <= max; n++)
        if (is_niven(n))
            printf("%d\n", n);
    return EXIT_SUCCESS;
}