Scanner sr = new Scanner(System.in); System.out.print("請輸入a的值:"); int a = sr.nextInt(); boolean is = true; if (a < 1) { System.out.println(a + "不是質數,因為他小於一"); } else { List<Integer> list = new ArrayList<Integer>(); for (int i = 2; i < a; i++) { if (a % i != 1 && a % i != a) { if (a % i == 0){ is=false; list.add(i); } } } if(is){ System.out.println("a是質數"); }else{ String yz=""; for (int i = 0; i < list.size(); i++) { if (yz=="") { yz=yz+list.get(i); }else{ yz=yz+","+list.get(i); } } System.out.println("a不是質數,因為他含有因子"+yz); } }
使用java編寫判斷自然數是否為素數的方式是,使用scanner來接受使用者輸入的數值,使用素數的演算法,例項如下:
Scanner sr = new Scanner(System.in); System.out.print("請輸入a的值:"); int a = sr.nextInt(); boolean is = true; if (a < 1) { System.out.println(a + "不是質數,因為他小於一"); } else { List<Integer> list = new ArrayList<Integer>(); for (int i = 2; i < a; i++) { if (a % i != 1 && a % i != a) { if (a % i == 0){ is=false; list.add(i); } } } if(is){ System.out.println("a是質數"); }else{ String yz=""; for (int i = 0; i < list.size(); i++) { if (yz=="") { yz=yz+list.get(i); }else{ yz=yz+","+list.get(i); } } System.out.println("a不是質數,因為他含有因子"+yz); } }
import java.util.Scanner;
public class Prime {
public static void main(String[] args) {
Scanner c = new Scanner(System.in);
System.out.println("請輸入一個大於3的整數:");
int num = c.nextInt();
for(int i=2;i<=num/2;i++){
if(num%i==0){
System.out.println(num+"不是素數");
}else{
System.out.println(num+"是素數");
}
}
}
}