TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
armstrong_number.cpp
1
19#include <cassert>
20#include <cmath>
21#include <iostream>
22
28int 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
43bool 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
67static 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
88int main() {
89 test(); // run self-test implementations
90 return 0;
91}
static void test()
Self-test implementations.
int main()
Main function.
bool is_armstrong(const T &number)
Checks if the given number is armstrong or not.
T sum(const std::vector< std::valarray< T > > &A)