php - Prime numbers up to a certain number

51

here is the problem, i need to find prime numbers up to a certain number and here is my code:

$a = 56;

for($i = 2; $i<=$a; $i++)
{
    if($i == 2)
    {
        echo "2</br>";
    }

    if($i == 3)
    {
        echo "3</br>";
    }

    if($i == 5)
    {
        echo "5</br>";
    }

    if($i == 7)
    {
        echo "7</br>";
    }

    for($j =3; $j <= ceil($i/2); $j = $j + 2)
    {
        if($i % 2 == 0)
        {
            break;
        }
        if($i % 3 == 0)
        {
            break;
        }
        if($i % 5 == 0)
        {
            break;
        }
        if($i % 7 == 0)
        {
            break;
        }
        else
        {
            echo "$i</br>";
            break;
        }
    }
}

It works fine, but it kinda seems like a brute force algorithm, doesnt it? Is there any other way to do this? Thanks for help!!!

641

Answer

Solution:

Suppose x is the limit (till which you want prime number)..

for($n=2;$n<=$x;$n++)
{
  $i=2; 
  while($i<=$n-1) 
  {
    if($n % $i == 0)
    break;
    $i++;
  }
  if($i==$num) 
  echo $n;   // $n is the prime number...
}

People are also looking for solutions to the problem: php - ZF1: Routes in database

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.