Primes --JAVA

题目:

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

题意:

写一个程序,判断给出的数字是不是素数,是素数输出yes,否则输出no;

一定要注意,当n<=0时结束,现在还活着就凭借着一口气,竟然被这一道弱爆的题卡死了,没仔细看题,一直认为是n==0时结束。。。。。丢脸

需要注意输出的格式;

代码如下:

JAVA:

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
	Scanner input=new Scanner(System.in);
	int kk=1;
	while(input.hasNext()) {
		int n=input.nextInt();
		if(n<=0)
			break;
		int flag=0;
		if(n<=2)
			flag=1;
		else {
			int m=(int)Math.sqrt(n);
			for(int i=2;i<=m;i++) {
				if(n%i==0) {
					flag=1;
					break;
				}
			}
		}
		System.out.print(kk+": ");
		kk++;
		if(flag==1)
			System.out.println("no");
		else
			System.out.println("yes");
	}
}
}

C++:

#include<stdio.h>
#include<math.h>

int main()
{
    int n,i;
    int k=1;
    while(~scanf("%d",&n))
    {
        if(n<=0)
            break;
        if(n<=2)
            printf("%d: no\n",k++);
        else
        {
            int m=sqrt(n);
            for(i=2; i<=m; i++)
            {
                if(n%i==0)
                    break;
            }
            if(i>m)
                printf("%d: yes\n",k++);
            else
                printf("%d: no\n",k++);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/titi2018815/article/details/83998229