c语言编程填空

c语言编程填空用循环语句
2025-03-12 16:18:10
推荐回答(2个)
回答1:

从main中调用可以看出, fun功能为判断参数m是否为素数,如果是返回真(1)否则返回假(0)

所以可以写成

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

注意,由于题目中没有包含math.h ,所以这个代码没用到常见的sqrt(m)作为边界,而是退一步用m/2作为边界.

另外, 素数算法很多, 这个题目也有很多正确的答案, 只要判断素数成功即可.

另一个变种:

int fun(int m)
{
    int n;
    if(m==2)return 1;
    if(!(m&1)) return 0;
    for(n = 3; n    {
        if(m%n==0) return 0; 
    }
    return 1;
}

回答2: