(一)求100內的素數:java
public void a() { for (int i = 2; i <= 100; i++) { int temp = (int) Math.sqrt(i); // 我把那個aqrt單獨提出來,這樣速度稍微快一點,雖然在100內變化不大,但若是是10000000內的素數呢? if (i <= 3) { System.out.println(i + " is a prime"); } else { for (int j = 2; j <= temp; j++) {// 把Math.sqrt(i)轉換爲int類形 if (i % j == 0) { break; } if (j >= temp) { System.out.println(i + " is a prime"); } } } } }
(二)求n-m間的素數code
public void sushu(int n ,int m){ for (int i = n; i < m; i++) { int temp = (int)Math.sqrt(i); if(i<=3){ System.out.println(i); } for (int j = 2; j <= temp; j++) { if(i%j==0){ break; } if(j>=temp){ System.out.println(i); } } } }