Student Of Fortune

Fastest algorithm Printing Prime's Numbers

Share on :
This tutorial discusses the print primes quickly. A prime number is required not only to 100 or 1000, but up to 100 million.

Sieve of Eratosthenes
After searching on Google, we found one of the classic algorithm to print the prime numbers. The algorithm is called the Sieve of Eratosthenes, I found on Wikipedia. Maybe this is not the fastest algorithm, but at least fast enough compared to when using modulus.

The following algorithm is quoted from Wikipedia.
Suppose we want to find all prime numbers between 1 to an integer n.

  1. Write down all the numbers, ranging from 1 to n. Suppose this is the list A.
  2. Create a list that is still blank, call it a list B.
  3. Strikeout number 1 from list A.
  4. Then write 2 on list B. Then streak 2 and all the increments from the list A
  5. The first number that has not crossed from the list A (eg 3) is prime. Write these numbers in list B, then streak this number and all the increments from list A.
  6. Repeat step 4 until all the numbers in list A are crossed.
Once completed, all numbers in list B is prime.
And here are examples of the application of the above algorithm in the programming language PHP. This script has been tested to show the prime numbers below 1,000,000 and successfully display it within 3 seconds.
See The Code  

  1. <?php
  2. function bilangan_prima($limit) {
  3. $prima = array();
  4. $prima_awal = array(2,3,5,7);
  5. for ($i=2; $i<=$limit; $i++)
  6. $prima[$i] = true;
  7. foreach ($prima_awal as $awal) {
  8. for ($i=2*$awal; $i<=$limit; $i+=$awal) {
  9. $prima[$i] = false;
  10. }
  11. }
  12. foreach ($prima as $bilangan=>$status) {
  13. if ($status) echo "$bilangan ";
  14. }
  15. }
  16. $start=mktime();
  17. bilangan_prima(1000000);
  18. $finish=mktime();
  19. $result=$finish-$start;
  20. echo "<br>Time: $result seconds";
  21. ?>

1 comments:

rectangular coordinate system said... September 3, 2012 at 10:34 PM

In all types of computer programming languages,prime numbers are used to make programs.Its easy to generate even numbers but to generate odd and prime numbers are little bit tricky.

Post a Comment and Don't Spam!

Dont Spam please

 
Recommended Post Slide Out For Blogger

Recent Comments

My Rank