Strong Number คือเลขที่ผลรวมของแฟกทอเรียลของแต่ละหลักเท่ากับตัวเลขนั้นเอง เช่น 145 = 1! + 4! + 5! = 1 + 24 + 120 = 145
ตัวอย่าง
Input: n = 124 → Output: No (1!+2!+4! = 27 ≠ 124) Input: n = 145 → Output: Yes (1!+4!+5! = 145)
แนวทางแก้ปัญหา
- แยกตัวเลขทีละหลักจากหลักหน่วย
- คำนวณแฟกทอเรียลของแต่ละหลัก
- รวมผลลัพธ์และเปรียบเทียบกับตัวเลขเดิม
อัลกอริทึม
- ฟังก์ชัน
factorial(int r)คำนวณแฟกทอเรียลด้วยลูป while - ฟังก์ชัน
check(int n)แยกหลัก คำนวณผลรวม และเปรียบเทียบ
โค้ดตัวอย่าง
#include <stdio.h>
int factorial(int r) {
int fact = 1;
while (r > 1) {
fact *= r;
r--;
}
return fact;
}
int check(int n) {
int temp = n, rem, result = 0;
while (temp) {
rem = temp % 10;
result += factorial(rem);
temp /= 10;
}
return (result == n) ? 1 : 0;
}
int main() {
int n = 145;
if (check(n))
printf("Yes it is a strong number\n");
else
printf("No it is not a strong number\n");
return 0;
}
ผลลัพธ์
Yes it is a strong number