TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
armstrong_number_templated.cpp
Go to the documentation of this file.
1
22#include <cassert>
23#include <cmath>
24#include <iostream>
25
30namespace dynamic_programming {
31
38template <typename T>
39bool is_armstrong(const T &number) {
40 int count = 0, temp = number, result = 0, rem = 0;
41
42 // Count the number of digits of the given number.
43 // For example: 153 would be 3 digits.
44 while (temp != 0) {
45 temp /= 10;
46 count++;
47 }
48
49 // Calculation for checking of armstrongs number i.e.
50 // in an n-digit number sum of the digits is raised to a power of `n` is
51 // equal to the original number.
52 temp = number;
53 while (temp != 0) {
54 rem = temp % 10;
55 result += static_cast<T>(std::pow(rem, count));
56 temp /= 10;
57 }
58
59 if (result == number) {
60 return true;
61 } else {
62 return false;
63 }
64}
65} // namespace dynamic_programming
66
71static void tests() {
72 assert(dynamic_programming::is_armstrong(153) == true);
73 assert(dynamic_programming::is_armstrong(1) == true);
74 assert(dynamic_programming::is_armstrong(0) == true);
75 assert(dynamic_programming::is_armstrong(370) == true);
76 assert(dynamic_programming::is_armstrong(1634) == true);
77 assert(dynamic_programming::is_armstrong(580) == false);
78 assert(dynamic_programming::is_armstrong(15) == false);
79 assert(dynamic_programming::is_armstrong(1024) == false);
80 assert(dynamic_programming::is_armstrong(989) == false);
81 assert(dynamic_programming::is_armstrong(103) == false);
82
83 std::cout << "All tests have successfully passed!\n";
84}
85
90int main() {
91 tests(); // run self-test implementations
92 return 0;
93}
static void tests()
Self-test implementations.
int main()
Main function.
Dynamic Programming algorithms.
bool is_armstrong(const T &number)
Checks if the given number is armstrong or not.