Prime Number in PHP


Q. Write a PHP program to check Prime Number or Not

<?php
// Define the number to check
$number = 29;
$isPrime = true;

// 0 and 1 are not prime
if ($number <= 1) {
    $isPrime = false;
} else {
    // Check divisibility from 2 to sqrt(number)
    for ($i = 2; $i <= sqrt($number); $i++) {
        if ($number % $i == 0) {
            $isPrime = false;
            break;
        }
    }
}

// Display the result
if ($isPrime) {
    echo "$number is a Prime Number.";
} else {
    echo "$number is NOT a Prime Number.";
}
?> 

Q. Write an algorithm to check Prime Number in PHP

1.Start
2.Define a number number
3. If number <= 1, set isPrime = false
4. Else loop from i = 2 to √number:
    a. If number % i == 0, set isPrime = false and break
5. If isPrime == true, print "Prime Number"
6. Else, print "Not a Prime Number"
7. End 



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.