题目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;
}
}
- 题目1
- 题目1
- 题目1
- 题目1
- 题目1
- 题目1
- 题目1
- 题目1
- 题目1 : Performance Log--微软题目
- Java面试题目(1)
- 笔试题目1
- moto面试题目1
- 面试题目1
- 常见面试题目1
- java面试题目1
- 数字电路笔试题目1
- JAVA经典题目1
- sql经典题目(1)
- 内部盒子居中
- 阿里巴巴java规范 第一版 2017-02-09记
- Java常见集合一览表
- 自制系列计算机图书
- moviebooking中的用户登录问题(Spring Security保护web应用)
- 题目1
- cef3 Binary Distributions下载及示例编译
- 淘淘商城系列——商品详情页面静态化方案分析
- Tomcat部署spring web项目,直接通过域名访问,不加项目名称
- PAT 甲级 1019. General Palindromic Number
- maven仓库
- Zookeeper实例原生API--同步获取子节点列表
- kotlin学习3(常量val、变量var)
- JQ获取表单的值