简体   繁体   English

请解释这个素数生成器代码是如何工作的(在C中)

[英]Please explain how this prime number generator code works (in C)

int prime (int poss_prime);  

int main() {  

    int poss_prime;  

    for (poss_prime = 2; poss_prime <= MAX_INT; poss_prime++) {  
        if (prime (poss_prime)) {  
            printf("%d ", poss_prime);  
        }  
    }  

    printf("\n\n");  
    return 0;  
}  

int prime (int poss_prime) {  

    int poss_factor;  

    for (poss_factor = 2; poss_factor <= poss_prime/2; poss_factor++) {  
        if (poss_prime % poss_factor == 0) {  
            return 0;  
        }  
    }  

    return 1;

}

I don't understand why the function can be used as the condition in the if statement, and why poss_prime is divided by two in the for loop condition. 我不明白为什么函数可以用作if语句中的条件,以及为什么poss_prime在for循环条件中除以2。 Thank you. 谢谢。

the function prime() has as its return type an integer. 函数prime()的返回类型为整数。 Putting the function call in the if statement is equivalent to 将函数调用放在if语句中等效于

int value = prime(possprime);
if(value)

It is just a neater way of doing so, if you do not subsequently require that return value. 如果您之后不需要返回值,那么这只是一种更简洁的方式。 logical expressions in C also accept numerical arguments. C中的逻辑表达式也接受数字参数。 0 is false, and any positive integer is true. 0为假,任何正整数都为真。 I don't know the result of a negative integer. 我不知道负整数的结果。

it would be clearer, however, if you used bool as the return type of prime, to make it clear it is a true/false situation. 但是,如果你使用bool作为素数的返回类型,那将更清楚,以明确它是一个真/假的情况。

As for the prime generator itself: It is checking for all factors of that number. 至于素数发生器本身:它正在检查该数字的所有因素。 It cannot have any factors greater than half the original value (excluding itself), which is why the for loop only goes to half of the possible primes value. 它不能有任何大于原始值一半的因子(不包括它自己),这就是为什么for循环只到达可能的素数值的一半。

Basic programming. 基本编程。

The function prime returns 1 or 0, depending on what it finds. 函数prime返回1或0,具体取决于它找到的内容。 In C, 0 means "false" and 1 means "true". 在C中,0表示“假”,1表示“真​​”。

Re the divide by 2, if there is any factor of the number, it must be half the number or less, since the smallest possible factor is 2. 除以2,如果有任何数字因子,它必须是数字的一半或更少,因为最小可能因子是2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM