C语言函数法求1000以内的全部水仙花数并判断求出的水仙花数是否为素数
时间: 2024-01-22 22:02:49 浏览: 83
C语言编写的菜单(登录密码、水仙花数、闰年、素数)
5星 · 资源好评率100%
以下是C语言函数法求1000以内的全部水仙花数并判断求出的水仙花数是否为素数的示例代码:
```c
#include <stdio.h>
#include <math.h>
// 判断是否为水仙花数
int isNarcissistic(int num) {
int sum = 0;
int digit = 0;
int temp = num;
while (temp > 0) {
digit = temp % 10;
sum += pow(digit, 3);
temp /= 10;
}
return sum == num;
}
// 判断是否为素数
int isPrime(int num) {
if (num < 2) {
return 0;
}
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
return 0;
}
}
return 1;
}
int main() {
// 求1000以内的水仙花数并判断是否为素数
for (int i = 100; i < 1000; i++) {
if (isNarcissistic(i)) {
printf("%d is a narcissistic number. ", i);
if (isPrime(i)) {
printf("And it is also a prime number.\n");
} else {
printf("But it is not a prime number.\n");
}
}
}
return 0;
}
```
输出结果如下:
```
153 is a narcissistic number. But it is not a prime number.
370 is a narcissistic number. But it is not a prime number.
371 is a narcissistic number. But it is not a prime number.
407 is a narcissistic number. But it is not a prime number.
```
阅读全文