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不是是素数;


代码<C语言>


#include<stdio.h>
#include<math.h>
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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值