Số Armstrong (Armstrong number) 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ụ số Armstrong:
3 = 3^1 153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153 407 = 4^3 + 0^3 + 7^3 = 64 + 0 + 343 = 407 1634 = 1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634
Chương trình hiển thị số Armstrong giữa hai khoảng:
Ví dụ
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int lowerbound, upperbound, digitSum, temp, remainderNum, digitNum;
lowerbound = 100;
upperbound = 500;
cout << "Số Armstrong giữa " << lowerbound << " và " << upperbound << " là: ";
for (int num = lowerbound; num <= upperbound; num++) {
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 << " ";
}
return 0;
}
Kết quả đầu ra
Số Armstrong giữa 100 và 500 là: 153 370 371 407
Trong chương trình, tìm số Armstrong giữa các khoảng cho trước. lowerbound và upperbound cho trước. Vòng for từ lowerbound đến upperbound, mỗi số kiểm tra xem có phải Armstrong không:
lowerbound = 100; upperbound = 500; cout << "Số Armstrong giữa " << lowerbound << " và " << upperbound << " là: "; for (int num = lowerbound; num <= upperbound; num++)
Trong vòng for, trước tiên tìm số chữ số của num. 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 (số chữ số):
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 thì không:
if (num == digitSum) cout << num << " ";