forked from ghostmkg/programming-language
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Armstrong_num.cpp
45 lines (40 loc) · 1.18 KB
/
Armstrong_num.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <bits/stdc++.h>
using namespace std;
// Function to check if a
// number is an Armstrong number
bool isArmstrong(int num) {
// Calculate the number of
// digits in the given number
int k = to_string(num).length();
// Initialize the sum of digits
// raised to the power of k to 0
int sum = 0;
// Copy the value of the input
// number to a temporary variable n
int n = num;
// Iterate through each
// digit of the number
while(n > 0){
// Extract the last
// digit of the number
int ld = n % 10;
// Add the digit raised to
// the power of k to the sum
sum += pow(ld, k);
// Remove the last digit
// from the number
n = n / 10;
}
// Check if the sum of digits raised to
// the power of k equals the original number
return sum == num ? true : false;
}
int main() {
int number = 153;
if (isArmstrong(number)) {
cout << number << " is an Armstrong number." << endl;
} else {
cout << number << " is not an Armstrong number." << endl;
}
return 0;
}