n자리의 숫자 x가 주어졌을 때 우리의 임무는 주어진 숫자의 플러스 퍼펙트 숫자인지 확인하는 것입니다. 숫자가 더하기 완전수인지 확인하기 위해 모든 숫자 d(d^n)의 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