阿姆斯特朗数 C 语言程序


我们有一个任务,要求我们检查用户输入的数字 n,它是不是阿姆斯特朗数。

阿姆斯特朗数是指所有数字的幂的和等于数字本身的顺序的数字。

以下是查找阿姆斯特朗数的一个简单表示法:

公式:

wxyz…. = pow(w, n) +pow(x, n) + pow(y, n) + pow(z, n) + …..

算法

START
Step 1-> Declare a function to find the value after power operation on the number
   int power(int a, int b)
      Loop while b>0
         Assign power =power * a
         Decrement b by 1
      End loop
      Return power
End
Step 2-> Declare a function to count the order of a number
   int count(int n)
      Declare and set i as 0
      Loop while n!=0
         Increment i by 1
         Divide n/10 and store back in n
      End loop
   Return i
End
Step 3-> Declare a function to check number is prime or not
   int armstrong(int n)
      Declare x and call function count(n) and assign the result to x
      Declare rem = 0 and m=0 set with zero
      Loop While n
         Set rem = n %10
         Set m = m + power(rem, x)
         Set n as n/ 10
      End Loop
   Return m;
End
Step 4-> Declare main
   int main(int argc, char const *argv[])
      Declare and set n = 1634
      Call function Armstrong and check if the value is equal
         Print “it is armstrong number
      End if
      Else
         Print number isn't an armstrong number
   End
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 armstrong(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 == armstrong(n)){
      printf("%d is an armstrong number 
",n);    }    else       printf("%d isn't an armstrong number
",n);    return 0; }

输出

1634 is an armstrong number

更新于: 2019 年 9 月 23 日

531 次浏览

开启你的 职业生涯

完成课程并获得认证

开始
广告
© . All rights reserved.