# C 程序：使用用户定义的函数检查质数或阿姆斯特朗数

> 原文： [https://www.programiz.com/c-programming/examples/prime-armstrong-function](https://www.programiz.com/c-programming/examples/prime-armstrong-function)

#### 在此示例中，您将学习通过创建两个单独的函数来检查整数是质数还是阿姆斯特朗数还是两者都是。

要理解此示例，您应该了解以下 [C 编程](/c-programming "C tutorial")主题：

*   [C `for`循环](/c-programming/c-for-loop)
*   [C `while`和`do...while`循环](/c-programming/c-do-while-loops)
*   [C `break`和`continue`](/c-programming/c-break-continue-statement)
*   [C 函数](/c-programming/c-functions)
*   [C 编程中用户定义函数的类型](/c-programming/types-user-defined-functions)

* * *

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

如果用户输入的数字是质数，则`checkPrimeNumber()`函数将返回`1`。 同样，如果用户输入的号码是阿姆斯特朗数，则`checkArmstrongNumber()`函数也会返回`1`。

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

*   [是否为质数](https://www.programiz.com/c-programming/examples/prime-number)
*   [是否为阿姆斯特朗数](https://www.programiz.com/c-programming/examples/check-armstrong-number)

* * *

## 示例：检查质数和阿姆斯特朗数

```c
#include <math.h>
#include <stdio.h>

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;
}
```

**输出**

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