Java基礎知識強化04:判斷101~200之間有多少素數

來源:互聯網
上載者:User

標籤:

判斷101~200之間有多少素數?

 1 package himi.hebao; 2  3 /** 4  * (1).編寫函數isPrime()用來判斷輸入資料是否為素數 (2).遍曆判斷101~200之間的資料是否為素數,並且計數count 5  *  6  * @author Administrator 7  *  8  */ 9 10 public class TestDemo05 {11 12     public static void main(String[] args) {13         int count = 0;14 15         for (int a = 101; a <= 200; a++) {16             if (isPrime(a)) {// 調用isPrime()方法  17                 System.out.println(a);18                 count++;19             }20 21         }22         System.out.println("輸出的101~200的素數一共有:");23         System.out.println(count);24 25     }26     /** 27      * <pre> 28      * 用於判斷一個數是否為素數,若為素數,返回true,否則返回false 29      * </pre> 30      *  31      * @param a 32      *            輸入的值 33      * @return true、false 34      */  35 36     private static boolean isPrime(int n) {37         boolean flag = true;38         if (n == 1) {39             flag = false;40         } else {41             for (int i = 2; i <= Math.sqrt(n); i++) {42                 if ((n % i) == 0 || n == 1) {// 若能被整除,則說明不是素數,返回false  43                     flag = false;44                     break;// 跳出迴圈,這是關鍵45                 } else {46                     flag = true;47                 }48             }49         }50         return flag;51 52     }53 54 }

 

Java基礎知識強化04:判斷101~200之間有多少素數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.