ให้ตัวเลข x กับจำนวน n หลัก หน้าที่ของเราคือตรวจสอบว่าหมายเลข Plus Perfect ของหมายเลขที่ระบุหรือไม่ ในการตรวจสอบว่าตัวเลขนั้นเป็นจำนวนบวกสมบูรณ์หรือไม่ เราจะหากำลังที่ n ของทุกหลัก d (d^n) แล้วจึงรวมตัวเลขทั้งหมด ถ้าผลรวมเท่ากับ n ตัวเลขนั้นก็คือเลขบวกสมบูรณ์ บวกกับตัวเลขที่สมบูรณ์แบบนั้นคล้ายกับการหาอาร์มสตรองของตัวเลขใด ๆ
ถูกใจในตัวอย่างด้านล่าง −

ตัวอย่าง
Input: 163 Output: Number is not a perfect_number Explanation: 1^3 + 6^3 + 3^3 is not equal to 163 Input: 371 Output: Number is a perfect_number Explanation: 3^3 + 7^3 +1^3 is equal to 371
แนวทางที่ใช้ด้านล่างมีดังนี้ −
- ขั้นตอนแรกคือการนับจำนวนหลักในการป้อนข้อมูลที่กำหนด
- ขั้นตอนที่สองคือการเพิ่มกำลังให้กับตัวเลขในจำนวนครั้งที่เท่ากันกับจำนวนหลักของอินพุต
- ขั้นตอนที่สามคือการบวกตัวเลขทั้งหมดและตรวจสอบว่าเท่ากันหรือไม่
อัลกอริทึม
Start In function int power(int a, int b) Step 1-> Declare and initialize power as 1 Step 2-> Loop While b>0 Set power = power * a Decrement b by 1 Step 3-> return power End function power In function int count(int n) Step 1-> Declare and Initialize i as 0 Step 2-> Loop While n!=0 Increment i by 1 Set n = n/10 End Loop Step 3-> Return i In function int perfect_number(int n) Step 1-> Declare and initialize x as count(n) Step 2-> Declare and initialize rem as 0 and m as 0 Step 3-> Loop While(n) Set rem as n %10 Set m as m + power(rem, x) Set n as n/ 10 End Loop Step 4-> Return m End Function perfect_number In Function int main(int argc, char const *argv[]) Step 1-> Initialize n as 1634 Step 2-> If n == perfect_number(n) then, Print "Number is a perfect_number " Step 3-> else Print "Number is not a perfect_number " End if End main Stop
ตัวอย่าง
#include <stdio.h>
int power(int a, int b) {
int power =1;
while(b>0) {
power *= a;
b--;
}
return power;
}
int count(int n) {
int i=0;
while(n!=0) {
i++;
n = n/10;
}
return i;
}
int perfect_number(int n) {
int x = count(n);
int rem = 0, m=0;
while(n) {
rem = n %10;
m += power(rem, x);
n /= 10;
}
return m;
}
int main(int argc, char const *argv[]) {
int n = 1634;
if(n == perfect_number(n)) {
printf("Number is a perfect_number\n");
}
else
printf("Number is not a perfect_number\n");
return 0;
} ผลลัพธ์
หากรันโค้ดด้านบน มันจะสร้างผลลัพธ์ต่อไปนี้ -
Number is a perfect_number