Search code examples
phploopsfor-loopnested-loopsnested-for-loop

Prime numbers using nested loops in PHP


I am a beginner coder and I am currently taking a course in basic PHP. I was practicing nested loops and one of the material questions included the following:
The program I was attempting to execute

I tried using the following code (which was one I used to check if a number entered through an html form is prime or not but I altered it to fit this question) but it seems incorrect as it only prints 2 and 3
here is the php code I wrote:

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
    <?php
        echo "<h3>The prime numbers up to 20 are:</h3>";
        echo "<p>1</p>";
        //Declaration of Variables
        $status=true;
        //Nested Loop and Conditions
        for( $i = 2; $i <= 20; $i++ ){
            for( $k = 2; $k < $i; $k++ ){
                if( $i % $k == 0 ){
                    $status=false;
                }
            }
            //Printing
            if($status==true)
                echo "<p>$i</p>";
        }
        ?>
    </body></html>

could anyone tell me what could I be doing wrong? I know this question seems simple, but please forgive me for I am still learning. This is also one of my first questions on the platform so forgive me if the formatting is a little off. Thank you in advance :)


Solution

  • welcome to the community

    I added 1 counter

    If i and k are equal to zero I increment the counter by 1 and exit the loop

    counter is not prime if it is not zero

    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
    </head>
    <body>
        <?php
        echo "<h3>The prime numbers up to 20 are:</h3>";
        echo "<p>1</p>";
        //Declaration of Variables
        $counter = 0;
        //Nested Loop and Conditions
        for( $i = 2; $i <= 20; $i++ ){
            $counter = 0;
            for( $k = 2; $k < $i; $k++ ){
                if( $i % $k == 0 ){
                    $counter +=1;
                    break;
                }
            }
            if($counter == 0){
                echo "<p>".$i."</p>";
            }
        }
    ?>