package com.Practices;
/****
* 1.判断一个数是否是素数
* 2.输入两个数,得到这两个数之间的所有素数,并打印出来
*/
import java.util.ArrayList;
import java.util.Scanner;
public class PrimeNum {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sin = new Scanner(System.in);
while(true) {
System.out.println("*************************************");
System.out.println("1.判断一个数是否是素数");
System.out.println("2.两个数之间的所有素数");
System.out.println("3.退出");
System.out.println("*************************************");
System.out.print("请选择你的操作:");
int OperNum = sin.nextInt();
while(OperNum > 3 || OperNum < 1) {
System.out.print("操作选择错误,请重新选择(1-3):");
OperNum = sin.nextInt();
}
switch(OperNum) {
case 1:{
System.out.print("请输入一个数字:");
int num = sin.nextInt();
while(num <= 1) {
System.out.print("判断一个数是否是素数,必须大于1,请重新输入一个大于1的数:");
num = sin.nextInt();
}
if (isPrimeNum(num))
System.out.println("Yes, " + num + " is a Prime Number !\n");
else
System.out.println("No, " + num + " is not a Prime Number !\n");
break;
}
case 2:{
System.out.print("请输入第一个大于1的数字:");
int num1 = sin.nextInt();
while(num1 <= 1) {
System.out.print("输入错误,请重新输入第一个大于1的整数:");
num1 = sin.nextInt();
}
System.out.print("请输入第二个大于1的数字:");
int num2 = sin.nextInt();
while(num2 <= 1) {
System.out.print("输入错误,请重新输入第而个大于1的整数:");
num2 = sin.nextInt();
}
SwapNum(num1, num2);
ArrayList PrimeList = NumberListIsPrimeNum(num1, num2);
System.out.print("请每行输出的素数的个数:");
int num = sin.nextInt();
while(num <= 1) {
System.out.print("输入错误,请重新输入每行输出的素数的个数:");
num = sin.nextInt();
}
PrintNum(PrimeList, num);
break;
}
case 3:
System.exit(0);
}
}
}
//判断一个数是否已是素数
public static boolean isPrimeNum(int num) {
boolean b = true;
for(int i=2; i if(num % i == 0) {
b = false;
break;
}
}
return b;
}
//得到某个数之间的所有素数
public static ArrayList NumberListIsPrimeNum(int minNum, int maxNum) {
ArrayList PrimeNumList = new ArrayList();
for(int i=minNum; i<=maxNum; i++) {
if(isPrimeNum(i))
PrimeNumList.add(i);
}
return PrimeNumList;
}
//比较两个数的大小
public static void SwapNum(int n, int m) {
if (n > m) {
int temp = n;
n = m;
m = temp;
}
}
//打印素数
public static void PrintNum(ArrayList intList, int num) {
System.out.println("总共有" + intList.size() + "个素数,分别是:");
for(int i=0; i System.out.print(intList.get(i) + "\t");
if ((i+1) % num == 0)
System.out.println();
}
System.out.println("\n");
}
}