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

更新於: 21-Oct-2019

231 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.