diff options
| author | Paulo Custodio <pauloscustodio@gmail.com> | 2021-06-22 23:49:49 +0100 |
|---|---|---|
| committer | Paulo Custodio <pauloscustodio@gmail.com> | 2021-06-22 23:49:49 +0100 |
| commit | ea25ccd04573a09c6c444929f65cd1e40deb07cb (patch) | |
| tree | f1aa6116e27acf7d6396362827e02be809e2f48f /challenge-007/paulo-custodio/cpp/ch-1.cpp | |
| parent | fa14fc2cde50bd8b44325f04fa6ecd92e7f23d63 (diff) | |
| download | perlweeklychallenge-club-ea25ccd04573a09c6c444929f65cd1e40deb07cb.tar.gz perlweeklychallenge-club-ea25ccd04573a09c6c444929f65cd1e40deb07cb.tar.bz2 perlweeklychallenge-club-ea25ccd04573a09c6c444929f65cd1e40deb07cb.zip | |
Add C++ solution to challenge 007
Diffstat (limited to 'challenge-007/paulo-custodio/cpp/ch-1.cpp')
| -rw-r--r-- | challenge-007/paulo-custodio/cpp/ch-1.cpp | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/challenge-007/paulo-custodio/cpp/ch-1.cpp b/challenge-007/paulo-custodio/cpp/ch-1.cpp new file mode 100644 index 0000000000..ce36d83869 --- /dev/null +++ b/challenge-007/paulo-custodio/cpp/ch-1.cpp @@ -0,0 +1,37 @@ +/* +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 <cassert> +#include <iostream> +using namespace std; + +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)) + cout << n << endl; + return EXIT_SUCCESS; +} |
