TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Toggle main menu visibility
Loading...
Searching...
No Matches
armstrong_number.cpp
1
19
#include <cassert>
20
#include <cmath>
21
#include <iostream>
22
28
int
number_of_digits(
int
num) {
29
int
total_digits = 0;
30
while
(num > 0) {
31
num = num / 10;
32
++total_digits;
33
}
34
return
total_digits;
35
}
36
43
bool
is_armstrong
(
int
number) {
44
// If the number is less than 0, then it is not an armstrong number.
45
if
(number < 0) {
46
return
false
;
47
}
48
49
int
sum
= 0;
50
int
temp = number;
51
// Finding the total number of digits in the number
52
int
total_digits = number_of_digits(number);
53
while
(temp > 0) {
54
int
rem = temp % 10;
55
// Finding each digit raised to the power total digit and add it to the
56
// total sum
57
sum
+=
static_cast<
int
>
(std::pow(rem, total_digits));
58
temp = temp / 10;
59
}
60
return
number ==
sum
;
61
}
62
67
static
void
test
() {
68
// is_armstrong(370) returns true.
69
assert(
is_armstrong
(370) ==
true
);
70
// is_armstrong(225) returns false.
71
assert(
is_armstrong
(225) ==
false
);
72
// is_armstrong(-23) returns false.
73
assert(
is_armstrong
(-23) ==
false
);
74
// is_armstrong(153) returns true.
75
assert(
is_armstrong
(153) ==
true
);
76
// is_armstrong(0) returns true.
77
assert(
is_armstrong
(0) ==
true
);
78
// is_armstrong(12) returns false.
79
assert(
is_armstrong
(12) ==
false
);
80
81
std::cout <<
"All tests have successfully passed!\n"
;
82
}
83
88
int
main
() {
89
test
();
// run self-test implementations
90
return
0;
91
}
test
void test()
Definition
caesar_cipher.cpp:100
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
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
machine_learning::sum
T sum(const std::vector< std::valarray< T > > &A)
Definition
vector_ops.hpp:232
math
armstrong_number.cpp
Generated by
1.18.0