ให้ตัวเลข 'n' เราต้องตรวจสอบว่าตัวเลขที่ให้นั้นเป็นตัวเลขที่แข็งแกร่งหรือไม่
จำนวนที่รัดกุมคือตัวเลขที่ผลรวมของแฟคทอเรียลของตัวเลขทั้งหมดเท่ากับตัวเลข 'n' แฟกทอเรียลบอกเป็นนัยเมื่อเราพบผลคูณของตัวเลขทั้งหมดด้านล่างตัวเลขนั้นรวมถึงตัวเลขนั้นด้วย และแสดงด้วย ! (เครื่องหมายอัศเจรีย์) เช่น 4! =4x3x2x1 =24.
ดังนั้น การหาจำนวนว่าเป็นตัวเลขที่แรงหรือไม่ เราต้องเลือกทุกหลักของตัวเลขเช่น 145 จากนั้นเราต้องเลือก 1, 4 และ 5 ตอนนี้เราจะหาแฟคทอเรียลของตัวเลขแต่ละตัวนั่นคือ 1! =1, 4! =24, 5! =120.
ตอนนี้เราจะสรุปได้ 1 + 24 + 120 เราจะได้ 145 เท่ากับค่าที่ใส่มา เราพูดได้ว่าตัวเลขนั้นเป็นตัวเลขที่รัดกุม
ตัวอย่าง
Input: n = 124 Output: No it is not a strong number Explanation: 1! + 2! + 4! = 27 which is not equal to n i.e, 124 Input: n = 145 Output: Yes it is a strong number Explanation: 1! + 4! + 5! = 145
แนวทางที่ใช้ด้านล่างมีดังต่อไปนี้ในการแก้ปัญหา −
เราจะ -
- นำแต่ละหลักโดยเริ่มจากตำแหน่งหน่วยแล้วหาแฟกทอเรียล
- เราจะบวกแฟกทอเรียลเหล่านั้นของแต่ละตัวเลข
- เปรียบเทียบผลลัพธ์กับตัวเลขเดิม หากเท่ากัน ตัวเลขจะเป็นตัวเลขที่รัดกุม มิฉะนั้นตัวเลขจะไม่แข็งแรง
อัลกอริทึม
START In Function int factorial(int r) Step1 -> Initialize int fact and set as 1 Step2-> Loop while r>1 Set fact as fact * r Decremnet r by 1 End Loop Step 3-> Return fact End Function factorial In Function int check(int n) Step 1-> Initialize int temp, rem and result, set result as 0 Step 2-> Set temp as n Step 3-> Loop while temp Set rem as temp % 10 Set result as result + factorial(rem) Set temp as temp/10 End loop Step 4-> If result == n then, Return 1 Step 5-> Else Return 0 End function check In main(int argc, char const *argv[]) Step 1-> Initialise and set n as 145 Step 2->If check(n) is valid then, Print "Yes it is a strong number” Step 3-> Else Print "no it is not a strong number” STOP
ตัวอย่าง
#include <stdio.h>
int factorial(int r) {
int fact = 1;
while(r>1) {
fact = fact * r;
r--;
}
return fact;
}
int check(int n) {
int temp, rem, result = 0;
temp = n;
while(temp) {
rem = temp % 10;
result = result + factorial(rem);
temp = temp/10;
}
if (result == n)
return 1;
else
return 0;
}
int main(int argc, char const *argv[]) {
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