Jump to content

prime numbers up to a certain number


Jahongir

Recommended Posts

Dear developers,

 

I was solving problems to improve my algorithmic abilities. So, here is one of them:

I need to "echo" all the prime numbers to the browser up to  certain number.

So, if the number is 8, for example, I need to echo 2,3,5 and 7.

 

here is my code:

 

$a = 100;
 
for($i = 2; $i<=$a; $i++)
{
    if($i == 2)
    {
        echo "2</br>";
    }
 
 
    for($j =3; $j <= ceil($i/2); $j = $j + 2)
    {
        if($i % 2 == 0)
        {
            break;
        }
        if ($i % $j == 0)
        {
            break;
        }
        else
        {
            continue;
        }
    }
}
 
not working properly!
 
Please Help !!!
Link to comment
Share on other sites

Do you mean this? :

$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? Thanks for help
Link to comment
Share on other sites

I had something like this in mind

$n = 56;
$numbers = array_fill_keys(range(2,$n),1);
$lim = ceil(sqrt($n));
for ($i=2; $i<$lim; $i++) {
    $k=2;
    while ($i*$k <= $n) {
        $numbers[$i*$k++] = 0;   
    }
}
echo join(', ', array_keys(array_filter($numbers)));

//--> 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.