Skip to content

Commit 81c3c41

Browse files
[FIX] Rewrite Armstrong Number algorithm to follow contribution guidelines
1 parent ba0d3ff commit 81c3c41

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

math/armstrong_number_shiwans.cpp

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/*
2+
* Armstrong Number Checker in C++
3+
*
4+
* An Armstrong number (narcissistic number) is a number equal to the sum of
5+
* its digits raised to the power of the number of digits.
6+
*
7+
* Example: 153 -> 1^3 + 5^3 + 3^3 = 153
8+
*
9+
* This implementation is beginner-friendly, with interactive input and tests.
10+
*/
11+
12+
#include <cassert>
13+
#include <cmath>
14+
#include <iostream>
15+
using namespace std;
16+
17+
// Function to count digits
18+
int count_digits(int num) {
19+
return (num == 0) ? 1 : static_cast<int>(log10(num)) + 1;
20+
}
21+
22+
// Function to check Armstrong number
23+
bool isArmstrong(int num) {
24+
if (num < 0)
25+
return false;
26+
27+
int sum = 0;
28+
int n = count_digits(num);
29+
int temp = num;
30+
31+
while (temp > 0) {
32+
int digit = temp % 10;
33+
sum += pow(digit, n);
34+
temp /= 10;
35+
}
36+
return sum == num;
37+
}
38+
39+
// Self-test function
40+
void test() {
41+
assert(isArmstrong(0) == true);
42+
assert(isArmstrong(153) == true);
43+
assert(isArmstrong(370) == true);
44+
assert(isArmstrong(225) == false);
45+
assert(isArmstrong(-23) == false);
46+
assert(isArmstrong(12) == false);
47+
cout << "All self-tests passed!\n";
48+
}
49+
50+
// Main function for interactive usage
51+
int main() {
52+
test(); // Run automated tests
53+
54+
int number;
55+
cout << "Enter a number to check if it is an Armstrong number: ";
56+
cin >> number;
57+
58+
if (isArmstrong(number))
59+
cout << number << " is an Armstrong number!\n";
60+
else
61+
cout << number << " is NOT an Armstrong number.\n";
62+
63+
return 0;
64+
}

0 commit comments

Comments
 (0)