0
Follow
0
View

Find prime numbers, so simple why do you keep getting errors(language -c language)

potatobroth 注册会员
2023-02-25 11:05

This answer refers to ChatGPT
Here is the code that uses C to input an integer not greater than 1000, then call a function to determine whether it is prime, and output the result:


#include 

int is_prime(int n) {
    if (n < 2) {
        return 0;
    }
    for (int i = 2; i <= n / 2; i++) {
        if (n % i == 0) {
            return 0;
        }
    }
    return 1;
}

int main() {
    int n;
    scanf("%d", &n);
    if (is_prime(n)) {
        printf("yes");
    } else {
        printf("no");
    }
    return 0;
}

The is_prime function in the

code is used to determine whether an integer is prime, returning 1 if it is, and 0 otherwise. The method of judging prime numbers starts from 2, and judges one by one whether the number can be evenly divided. If it can be divided, it is not prime and returns 0; otherwise, it continues to judge until n/2. If it is not evenly divided, it is prime and returns 1.

In the main function, we first read an integer using the scanf function, then call the is_prime function to determine whether the number is prime, and finally print either yes or no based on the result.

sggstz 注册会员
2023-02-25 11:05

if(x = = 0 | | x = = 1) instead of the if(x< 2), integer numbers may also be less than 0
and else from the function delete!(# 2 must be deleted!! Remove # 1!)

About the Author

Question Info

Publish Time
2023-02-25 11:05
Update Time
2023-02-25 11:05