Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ แสดงเลขอาร์มสตรอง (Armstrong Numbers) ระหว่างสองช่วง


Armstrong Number คือเลขที่ผลรวมของแต่ละหลักยกกำลังจำนวนหลัก = เลขเดิม

ตัวอย่าง:

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

ตัวอย่างโค้ด

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    int lowerbound, upperbound, digitSum, temp, remainderNum, digitNum;
    lowerbound = 100;
    upperbound = 500;
    cout << "Armstrong Numbers between " << lowerbound << " and " << upperbound << " are: ";
    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;
}

ผลลัพธ์

Armstrong Numbers between 100 and 500 are: 153 370 371 407

อธิบายขั้นตอน

  1. กำหนดช่วง lowerbound=100, upperbound=500
  2. for loop วน num = lowerbound ถึง upperbound
  3. while loop แรก: นับจำนวนหลัก (digitNum) โดยหาร 10 ซ้ำ
  4. while loop ที่สอง: คำนวณ digitSum = Σ (digit^digitNum)
  5. ถ้า num == digitSum → เป็น Armstrong พิมพ์ออกมา
// นับจำนวนหลัก
temp = num; digitNum = 0;
while (temp != 0) { digitNum++; temp = temp/10; }

// คำนวณ digitSum
temp = num; digitSum = 0;
while (temp != 0) {
    remainderNum = temp % 10;
    digitSum = digitSum + pow(remainderNum, digitNum);
    temp = temp / 10;
}

// ตรวจสอบ
if (num == digitSum) cout << num << " ";