File tree Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments