Primes

Primes

Time Limit : 1000/1000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 48   Accepted Submission(s) : 34
Problem Description
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.
 

 

Input
Each input line contains a single integer. The list of integers is terminated with a number<= 0. You may assume that the input contains at most 250 numbers and each number is less than or equal to 16000.
 

 

Output
The output should consists of one line for every number, where each line first lists the problem number, followed by a colon and space, followed by "yes" or "no".
 

 

Sample Input
1
2
3
4
5
17
0
 

 

Sample Output
1: no
2: no
3: yes
4: no
5: yes
6: yes
 
 

 

Source
2008 “Sunline Cup” National Invitational Contest - Warm Up
题目大意:
输入一个数,判断该数字是不是素数,是的话输出yes,反之no。(题目要求1,2,都不是素数)。
做这一题,因为题目所要求的的素数范围不大,不超过16000,所以,可以直接采用素数筛选,每一个数字存放在对应的数组中,是素数的数组,对应的数组的值变成一,反之,变成0.然后输出的时候,只需要判断该数字所对应数组中存放的数组,是1还是0,就可以得出答案;
 1 #include <stdio.h>
 2 int main()
 3 {
 4     int i,j,a[16005]={0},NUM,t=1;  
 5     for(i=1;i<=16000;i++)/*素数筛选,找出该范围内所有的素数*/
 6         a[i]=1;
 7     a[1]=0;             /*题目所要求的*/
 8     for(i=2;i<=16000;i++)
 9         if(a[i])
10             for(j=i+i;j<=16000;j+=i)
11                 a[j]=0;
12     /*for(i=2;i<=16000;i++)
13         if(a[i])
14             printf("%d ",i);*/
15     a[2]=0;            /*题目所要求的*/
16     for(t=1;scanf("%d",&NUM)!=EOF&&NUM>0;t++)/*输入数字,判断该位置的数值即可得出答案*/
17     {
18         printf("%d: ",t);
19         if(a[NUM])
20             printf("yes\n");
21         else
22             printf("no\n");
23     }
24     return 0;
25 }
View Code

 

posted @ 2014-08-22 13:02  Wurq  阅读(261)  评论(0编辑  收藏  举报