C程序来检查完全过剩数
对于给定的 n 位数 x,我们的任务是检查给定的数是否是完全过剩数。为了检查这个数是否是完全过剩数,我们找到每个数字 d 的 n 次方 (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
"); } else printf("Number is not a perfect_number
"); return 0; }
输出
如果运行以上代码,它将会生成以下输出 −
Number is a perfect_number
广告