Số Armstrong là số mà tổng các chữ số lũy thừa theo tổng số chữ số bằng chính số đó. Ví dụ:
3 = 3^1 153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153 371 = 3^3 + 7^3 + 1^3 = 27 + 343 + 1 = 371 407 = 4^3 + 0^3 + 7^3 = 64 + 0 + 343 = 407
Chương trình kiểm tra một số có phải Armstrong hay không:
Ví dụ
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int num = 153, digitSum, temp, remainderNum, digitNum;
temp = num;
digitNum = 0;
while (temp != 0) {
digitNum++;
temp = temp / 10;
}
temp = num;
digitSum = 0;
while (temp != 0) {
remainderNum = temp % 10;
digitSum = digitSum + pow(remainderNum, digitNum);
temp = temp / 10;
}
if (num == digitSum)
cout << num << " là số Armstrong";
else
cout << num << " không phải số Armstrong";
return 0;
}
Kết quả đầu ra
153 là số Armstrong
Trong chương trình, xác định số cho trước có phải Armstrong không. Đầu tiên tìm số chữ số. Tăng digitNum cho mỗi chữ số:
temp = num;
digitNum = 0;
while (temp != 0) {
digitNum++;
temp = temp / 10;
}
Sau khi biết số chữ số, tính digitSum bằng cách cộng từng chữ số lũy thừa digitNum:
temp = num;
digitSum = 0;
while (temp != 0) {
remainderNum = temp % 10;
digitSum = digitSum + pow(remainderNum, digitNum);
temp = temp / 10;
}
Nếu số bằng digitSum thì là Armstrong, in ra. Ngược lại không phải:
if (num == digitSum) cout << num << " là số Armstrong"; else cout << num << " không phải số Armstrong";