計算100以內的質數
1.質數:大於1的整數中,只能被自己和1整除的數為質數。
如果這個數,對比自己小1至2之間的數字,進行求余運算,結果都不等於0,則可以判斷該數為質數。
1 public class Zhishu { 2 public static void main(String[] args) { 3 int count= 0; 4 for(int n=2;n<=100;n++){ 5 boolean isTrue = true; 6 for(int t=n-1;t>1;t--){ 7 if(n%t==0){ 8 isTrue = false; 9 } 10 } 11 if(isTrue==true){ 12 count++; 13 System.out.println("this is a Zhishu "+n); 14 } 15 } 16 System.out.println("count is "+count); 17 } 18 }
運行結果顯示所有質數,共25個。
2.利用一個定理——如果一個數是合數,那么它的最小質因數肯定小於等於他的平方根。例如:50,最小質因數是2,2<50的開根號
再比如:15,最小質因數是3,3<15的開根號
合數是與質數相對應的自然數。一個大於1的自然數如果它不是合數,則它是質數。
上面的定理是說,如果一個數能被它的最小質因數整除的話,那它肯定是合數,即不是質數。所以判斷一個數是否是質數,只需判斷它是否能被小於它開跟后后的所有數整除,這樣做的運算就會少了很多,因此效率也高了很多。
1 public class Zhishu { 2 public static void main(String[] args) { 3 int count= 0; 4 boolean isTrue = true; 5 for(int n = 2;n<=100;n++){ 6 for(int t = 2;t<=(int)Math.sqrt(n);t++){ 7 if(n%t==0){ 8 isTrue = false; 9 } 10 if(isTrue==true){ 11 count++; 12 System.out.println("this is a Zhishu "+n); 13 } 14 } 15 System.out.println("count is "+count); 16 } 17 } 18 }
運行結果顯示所有質數,共25個。