演算法之求質數(Java語言)

來源:互聯網
上載者:User

標籤:ima   其他   string   get   title   語言   tps   overflow   strong   

質數(Prime number)

 

又稱素數,指在大於1的自然數中,除了1和該數自身外,無法被其他自然數整除的數(也可定義為只有1與該數本身兩個因數的數)。

 

演算法原理

驗證一個數字 n 是否為素數的一種簡單但緩慢的方法為試除法。此一方法會測試 n 是否為任一在2與之間的整數之倍數。

 

實現樣本(Java語言)

 

 1 public class PrimeNumberExample { 2  3     public static boolean isPrime(long n) { 4         5         if(n > 2 && (n & 1) == 0) 6            return false; 7         /* 運用試除法: 8          * 1.只有奇數需要被測試 9          * 2.測試範圍從2與根號{n},反之亦然 */10         for(int i = 3; i * i <= n; i += 2)11             if (n % i == 0) 12                 return false;13         return true;14     }15     16     public static void main(String[] args) {17         int which=0;18         for(int i=2;i<=1000;i++){19             if(isPrime(i)){        20                 which++;21                 if(which % 10 == 0 ){System.out.println();}22                 System.out.print(i+", ");23             }24         }25         System.out.println();26         System.out.print("共有"+which+"個質數.");27     }28 29 }

結果

 

 

2, 3, 5, 7, 11, 13, 17, 19, 23,
29, 31, 37, 41, 43, 47, 53, 59, 61, 67,
71, 73, 79, 83, 89, 97, 101, 103, 107, 109,
113, 127, 131, 137, 139, 149, 151, 157, 163, 167,
173, 179, 181, 191, 193, 197, 199, 211, 223, 227,
229, 233, 239, 241, 251, 257, 263, 269, 271, 277,
281, 283, 293, 307, 311, 313, 317, 331, 337, 347,
349, 353, 359, 367, 373, 379, 383, 389, 397, 401,
409, 419, 421, 431, 433, 439, 443, 449, 457, 461,
463, 467, 479, 487, 491, 499, 503, 509, 521, 523,
541, 547, 557, 563, 569, 571, 577, 587, 593, 599,
601, 607, 613, 617, 619, 631, 641, 643, 647, 653,
659, 661, 673, 677, 683, 691, 701, 709, 719, 727,
733, 739, 743, 751, 757, 761, 769, 773, 787, 797,
809, 811, 821, 823, 827, 829, 839, 853, 857, 859,
863, 877, 881, 883, 887, 907, 911, 919, 929, 937,
941, 947, 953, 967, 971, 977, 983, 991, 997,
共有168個質數.

 

參考連結: 

質數-維基百科: https://zh.wikipedia.org/wiki/%E7%B4%A0%E6%95%B0

Very simple prime number test: http://stackoverflow.com/questions/14650360/very-simple-prime-number-test-i-think-im-not-understanding-the-for-loop

 

 

 

演算法之求質數(Java語言)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.