C language: Determine whether a number is prime (3 methods, including comments)

First of all, we must understand the definition of a prime number: a number that has no other factors except 1 and itself, that is, it cannot be divided by other numbers.

Also note that 1 is not a prime number.

The following are the 3 codes for judging prime numbers:

1. Please note that the initial value assigned to m cannot be 1, because 1 is a factor of any number and can be divided by any number. If the initial value is 1, the loop ends in the first step, and all the number output results are not prime numbers (except 1), which cannot be used for judgment.

#include<stdio.h>
int main()
{
    int i, m;
    printf("请输入一个大于一的整数:");
        scanf("%d", &i);
    for (m = 2; m <= i; m++)
        if (i % m == 0)//当2-m之间遇到因数时,结束循环
            break;
    if (m == i)//如果遇到的因数就是它本身,是素数
        printf("%d是素数", i);
    else
        printf("%d不是素数", i);
    return 0;

}

2. In this code, the function of count is to calculate the number of factors of this number. If it is 2, that is, there is only 1 and itself, which is a prime number.

#include<stdio.h>
int main()
{
    int i, m;
    int count = 0;
    printf("请输入一个大于1的整数:\n");
    scanf("%d", &i);
    for (m = 1; m <= i; m++)
    {
        if (i % m == 0)//统计要判断的数的因数个数
            count++;

    }
    if (count == 2)//如果只有2个因数
        printf("%d是素数", i);
    else
        printf("%d不是素数", i);
        
    return 0;
        
}

3. This code refers to the square root sqrt function, so math.h must be quoted; take it in half to save space.

#include<stdio.h>
#include<math.h>//求平方根需要引用
int main()
{
    int n, m, i;//定义需要用到的变量
    printf("请输入一个大于1的正整数:");
    scanf("%d", &n);//输入要判断的数
    m = sqrt(n);//求输入数的平方根
    for (i = 2; i <= m; i++)//取2-m之间的每一个整数
        if (n % i == 0)//判断能否整除n
            break;//非素数,跳出循环
    if (i > m)
        printf("%d是素数!\n", n);//循环正常结束,是素数
    else
        printf("%d不是素数!\n", n);//循环中途退出,不是素数
    return 0;
}

Guess you like

Origin blog.csdn.net/m0_75115696/article/details/128694800