STEP #1

(1/2)

此处切换ai服务商,可对比多家ai的回复,取最优解。

上一步下一步关闭
酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

a prime number is a number greater than one that is divisible only by 1 and by itself. that means that a prime number is positive. let's define a pseudo-prime number as a number that can be negative but also is divisible only by 1 and by absolute value of itself. write a function is_prime that checks if a number is pseudo-prime or not. the function returns 1 if number is pseudo-prime and -1 otherwise. the function should work correctly for any signed numbers.用c语言

以下是用 C 语言实现的 `is_prime` 函数: ```c #include <stdio.h> // 定义判断是否为伪素数的函数 int is_prime(int num) { // 如果数字小于 0,取其绝对值 if (num < 0) { num = -num; } // 0 和 1 不是伪素数 if (num == 0 || num == 1) { return -1; } // 从 2 到数字的平方根遍历 for (int i = 2; i * i <= num; i++) { // 如果能被整除,不是伪素数 if (num % i == 0) { return -1; } } // 都不能整除,是伪素数 return 1; } int main() { int num; printf("请输入一个数字: "); scanf("%d", &num); int result = is_prime(num); if (result == 1) { printf("%d 是伪素数\n", num); } else { printf("%d 不是伪素数\n", num); } return 0; } ``` 额外需要注意的逻辑点: 1. 对于负数的处理,要先取其绝对值进行判断。 2. 在判断是否能被整除时,只需要遍历到数字的平方根即可,减少计算量。 3. 注意输入数字的合法性,比如是否为整数等。 [2024-12-15 19:28:35 | AI写代码神器 | 364点数解答]

相关提问