Primes(素数)

题目

Write a program to read in a list of integers and determine whether or not each number is prime. A number, n, is prime if its only divisors are 1 and n. For this problem, the numbers 1 and 2 are not considered primes. 


个人理解


         如果a[i]不能被 2 ~sqrt(a[i])间任一整数整除,a[i]必定是素数。例如判别18是是否为素数,只需使18被2~4之间的每一个整数去除,由于都可以整除,可以判定18不是是素数;


代码


#include
#include
void main()
{
    int i,j,b,x;
    int a[250];
    for(i=0;i<250;i++)
    {
        scanf("%d",&a[i]);//输入数据
        if(a[i]<=0)
        {
            break;
        }
        b=(int)sqrt(a[i]);//求其平方根
        for(j=2;j<=b+1;j++)//进行素数的判断
        {
            if(a[i]%j==0)
            {
                x=0;
                break;
            }
            else
                x=1;

        }
        if(a[i]==1)
            x=0;
        if(x)
        {
            printf("%d: yes\n",++i);
            --i;
        }
        else
        {
            printf("%d: no\n",++i);
            --i;
        }
     }
}

提交结果

Result Accepted

Memory 1816K

Time 0MS

Language C

Code length 855B




你可能感兴趣的:(C语言)