Armstrong Number: เลข n หลัก ที่ผลรวมของแต่ละหลักยกกำลัง n เท่ากับตัวเลขนั้นเอง
ตัวอย่าง
153 = 1³ + 5³ + 3³ = 1 + 125 + 27 = 153 ✓ 1634 = 1⁴ + 6⁴ + 3⁴ + 4⁴ = 1 + 1296 + 81 + 256 = 1634 ✓
อัลกอริทึม
- นับจำนวนหลัก (order) = n
- แยกแต่ละหลัก คำนวณ digitⁿ สะสม
- เปรียบเทียบกับตัวเลขเดิม
โค้ดตัวอย่าง
#include <stdio.h>
int power(int base, int exp) {
int res = 1;
while (exp--) res *= base;
return res;
}
int count_digits(int n) {
int c = 0;
while (n) { n /= 10; c++; }
return c;
}
int is_armstrong(int n) {
int original = n, digits = count_digits(n), sum = 0;
while (n) {
int d = n % 10;
sum += power(d, digits);
n /= 10;
}
return sum == original;
}
int main() {
int n = 1634;
printf("%d is %san Armstrong number\n", n, is_armstrong(n) ? "" : "not ");
return 0;
}
ผลลัพธ์
1634 is an Armstrong number