题目1

来源:互联网 发布:盛世网络剧完整版资源 编辑:程序博客网 时间:2024/06/11 17:40

题目:

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.

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.

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".

个人理解:有两个比较关键的点,一个是如何以输入一个数字列表并输出每个的判断结果,另一个则是如何写一个方法正确判断素数。另外需要注意的则是最终输出不包含最后输入的素数,所以在for循环中应当为i-1。

代码:package contest;
import java.util.*;
import java.awt.*;
import java.io.*;
public class day1 {
public static void main(String[] args){
int[] arr=new int[250];
int i=0;
        Scanner sc = new Scanner(System.in); 
        System.out.println("请输入数字列表");
        
        //System.out.println(arr[0]);
        do {
         arr[i]=sc.nextInt();
i++;
} while (arr[i-1]>0);
        for (int j = 0; j < i-1; j++) {
System.out.print(arr[j]+":\t");

if(isPrime(arr[j]))System.out.println("yes");
else System.out.println("no");
}
        
}
   public static boolean isPrime(int a) {  
   
        boolean flag = true;  
  
        if (a < 2) {// 素数不小于2  
            return false;  
        } else {  
  
            for (int i = 2; i <= Math.sqrt(a); i++) {  
  
                if (a % i == 0) {// 若能被整除,则说明不是素数,返回false  
  
                    flag = false;  
                    break;// 跳出循环  
                }  
            }  
        }  
        return flag;  
    }  
}  


原创粉丝点击