📜  C程序,使用用户定义的功能检查素数或阿姆斯壮数

📅  最后修改于: 2020-10-04 11:42:05             🧑  作者: Mango

在此示例中,您将学习通过创建两个单独的函数来检查整数是质数还是Armstrong还是两者都是。

在该程序中,创建了两个用户定义的函数checkPrimeNumber()checkArmstrongNumber()

如果用户输入的数字是质数,则checkPrimeNumber() 函数将返回1 。同样,如果用户输入的数字是阿姆斯壮数字,则checkArmstrongNumber( ) 函数也返回1

访问这些页面以了解检查数字是否为

  • 是否有质数
  • 一个阿姆斯壮号

示例:检查Prime和Armstrong
#include 
#include 

int checkPrimeNumber(int n);
int checkArmstrongNumber(int n);

int main() {
   int n, flag;
   printf("Enter a positive integer: ");
   scanf("%d", &n);

   // check prime number
   flag = checkPrimeNumber(n);
   if (flag == 1)
      printf("%d is a prime number.\n", n);
   else
      printf("%d is not a prime number.\n", n);

   // check Armstrong number
   flag = checkArmstrongNumber(n);
   if (flag == 1)
      printf("%d is an Armstrong number.", n);
   else
      printf("%d is not an Armstrong number.", n);
   return 0;
}

// function to check prime number
int checkPrimeNumber(int n) {
   int i, flag = 1, squareRoot;

   // computing the square root
   squareRoot = sqrt(n);
   for (i = 2; i <= squareRoot; ++i) {
      // condition for non-prime number
      if (n % i == 0) {
         flag = 0;
         break;
      }
   }
   return flag;
}

// function to check Armstrong number
int checkArmstrongNumber(int num) {
   int originalNum, remainder, n = 0, flag;
   double result = 0.0;

   // store the number of digits of num in n
   for (originalNum = num; originalNum != 0; ++n) {
      originalNum /= 10;
   }

   for (originalNum = num; originalNum != 0; originalNum /= 10) {
      remainder = originalNum % 10;

      // store the sum of the power of individual digits in result
      result += pow(remainder, n);
   }

   // condition for Armstrong number
   if (round(result) == num)
      flag = 1;
   else
      flag = 0;
   return flag;
}

输出

Enter a positive integer: 407
407 is not a prime number.
407 is an Armstrong number.