方式一
//輸出1-100中質數 public class PrimeNum { public static void main(String[] args) { int count = 0; for(int i = 2 ; i <= 100;i++) { boolean flag = true; //1、假設是質數 for(int j = 2; j <= (int)Math.sqrt(i); j++) { //Math.squart()取平方根 if(i % j == 0) { flag = false; //2、改為不是質數 break; } } if(flag) { //3、得結論 count++; System.out.print(i + ","); } } } }
方式二:
System.out.println("請輸入");
Scanner scanner=new Scanner(System.in);
int a=scanner.nextInt();
int count=0;
int j;
for(int i=2;i<=a;i++){
j=2;
for(int n=2;n<i;n++){
if(i%n!=0){
j++;
}
}
if(j==i){
count++;
}
}
System.out.println(count);
