import java.util.Scanner;
public class PrimeNumbers {
public static boolean prime(int num) {
boolean flag = true;
for(int i=2;i<=num/2;i++) {
if(num%i==0) {
flag = false;
break;
}
}
return flag;
}
public static void main(String[] args) {
String separator = "";
Scanner scan = new Scanner(System.in);
System.out.println("First num:");
int low = scan.nextInt();
System.out.println("Second num:");
int high = scan.nextInt();
if(low>high||high<=0||low<0||(high-low) == 1) {
System.out.println("Invalid input");
System.exit(0);
}
while(low<high) {
if(prime(low)==true) {
System.out.printf(separator+"%d",low);
separator = ",";
}
low++;
}
}
}
示例:
first num:1
second num:10
Output: 1,2,3,5,7
我的要求是,我需要检查'second num'输入是否为素数,如果不是素数,则打印下一个素数。
示例:
first num:1
second num:
Output: 1,2,3,5,7,11
int lastNumber = high;
if(!prime(lastNumber))
{
while(!prime(++lastNumber));
// now you have to prime number after the high or that number itself if it
//is the prime
}
// now print all numbers and lastNumber in the last
You did num/2 if the first loop which is good for performance but you can increase
performance even more you can do int sqrt = sqrt(num) , now cast it to int and use it
int the loop
so if num is 100 in your case you will be doing 50 checks , but in sqrt case on 10
checks