判断素数, 为什么输入327得到的结果是yes

img


为什么输入327得到的结果是yes,输入简单的数就是对的?(1223685555凑字数)

if (n=i)
=>
if (n == i)

你这个输出yes应该在for循环外面,就是for循环里面所有的数字都不是n的因子的时候,才能输出yes,而且你if里面应该写两个=才是判断,一个=是赋值

【以下回答由 GPT 生成】

#include<stdio.h>

int main(){
    int i, n=13;
    scanf("%d", &n);

    if (n > 3){
        // Assume n is prime at the beginning
        int isPrime = 1;

        for (i = 2; i < n; i++){
            if (n % i == 0){
                // If n is divisible by any number between 2 and n-1,
                // it is not prime. Set isPrime to false and break the loop.
                isPrime = 0;
                break;
            }
        }

        // Check if isPrime is still true and n is not divisible by any number
        if (isPrime == 1){
            printf("yes");
        } else {
            printf("no");
        }
    } else {
        printf("error");
    }
    return 0;
}

Explanation: In the provided code, the issue lies with the placement of the if (n == i) condition. This condition should be outside the loop to check if n is equal to i after the loop has finished executing. Currently, it is inside the loop, which causes "yes" to be printed multiple times for non-prime numbers.

To optimize the code, I have introduced a boolean variable isPrime to keep track of whether n is prime or not. I assume n is prime at the beginning (set isPrime to 1) and iterate through all numbers between 2 and n-1 to check if n is divisible by any number. If it is divisible, isPrime is set to 0 and the loop is exited. After the loop, we check the value of isPrime and print "yes" if it is still 1 (indicating that n is prime), and "no" otherwise.

This modified code should provide the correct results when checking for prime numbers.


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^