PHP, MySQL, Drupal, .htaccess, Robots.txt, Phponwebsites: Find prime numbers between 1 and 100 in PHP

26 Aug 2015

Find prime numbers between 1 and 100 in PHP

        This blog describes how to find prime numbers between 1 and 100 using PHP. Prime number is a number which is divided by 1 and itself.  Consider the number 5. It is prime number because it can be divided by 1 and 5.

PHP program for prime numbers:


       Consider the below program which is used to find prime numbers from 1 to 100.

<?php
    for($i = 1; $i <= 100; $i++)
      $mm = 0;
      for($j = 2; $j <= $i/2; $j++) {
        //only not prime numbers
                if ($i % $j == 0) {
                  $mm++;
                  break;
                }
      }
      if ($mm == 0) {
                echo"$i is prime number<br/>";
      }
    }
  ?>

       In above program, if a number is divided by any number except 1 and itself, then it is not prime number. Otherwise it is a prime number.


PHP program for find prime numbers from a to 100


        Now you got prime numbers between 1 and 100 using PHP.
Related Post

9 comments:

  1. better optimisation is to search not to half of the number but to root of a number. There won't be any dividers later on

    ReplyDelete
  2. Why not Sieve of Eratosthenes? It's more efficient:
    http://www.hashbangcode.com/blog/sieve-eratosthenes-php

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Much more efficient:

    <?php

    function is_prime($num)
    {
        $max = (int)sqrt($num);
        for($i = $max; $i >= 2; --$i) 
        {
            if ($num % $i == 0)
            {
                return false;
            }
        }
        return true;
    }

    // The function returns the correct value,
    // but skippig them will enable skipping even numbers
    echo"1 is prime number<br>2 is prime number<br>";

    for($i = 3; $i <= 100; $i+=2)
    {
        if (is_prime($i))
        {
            echo"$i is prime number<br>";
        }
    }

    ReplyDelete
  5. 1 is neither prime nor composite.

    ReplyDelete
  6. opening brace missing after i loop!!!!

    ReplyDelete