題目:判斷101-200之間有多少個素數,並輸出所有素數。


程序分析:判斷素數的方法:用一個數分別去除2到sqrt(這個數),如果能被整除,則表明此數不是素數,反之是素數

 

public class SingleNum{
	public static void main(String[] args) {
		int count = 0;
		for(int i=101;i<200;i++) {
			//默認是素數
			boolean flag = true;
			for(int j=2;j<=Math.sqrt(i);j++) {
				if(i%j == 0) {
					//能整除
					flag = false;
				}
			}
			if(flag) {
				count +=1;
				System.out.print(i+",");
			}
		}
		
		System.out.println("\n有"+count+"個素數");
	}
}

 

  

 

輸出結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM