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
30
namespace
dynamic_programming
{
31
38
template
<
typename
T>
39
bool
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
71
static
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
90
int
main
() {
91
tests
();
// run self-test implementations
92
return
0;
93
}
tests
static void tests()
Self-test implementations.
Definition
armstrong_number_templated.cpp:71
main
int main()
Main function.
Definition
armstrong_number_templated.cpp:90
dynamic_programming
Dynamic Programming algorithms.
dynamic_programming::is_armstrong
bool is_armstrong(const T &number)
Checks if the given number is armstrong or not.
Definition
armstrong_number_templated.cpp:39
dynamic_programming
armstrong_number_templated.cpp
Generated by
1.12.0