+

PHP Check if a number is prime

Examples:
Input: 21 Output: Not Prime Input: 31 Output: Prime
Simple Method:
A simple solution is to iterate over all the numbers from 2 to n / 2 and, for each number, check if it divides n. If we find any number that is divisible, we will return 0 (false), otherwise we will return 1 (true).Below is the PHP implementation of this approach:
// PHP code to check if a number is prime or not // function to check if the number is primary or not function primeCheck ( $number ) { if ( $number == 1) return 0; for ( $i = 2; $i < = $number / 2; $i ++) { if ( $number % $i == 0) return 0; } return 1; }  
// Driver code $number = 31; $flag = primeCheck ( $number ); if ( $flag == 1) echo "Prime" ; else echo " Not Prime "?>
Output:
Prime  Time complexity: O (n)Efficient method:
We can optimize the above approach by observing that instead of checking up to n we can check to sqrt (n), since the larger factor n must be a multiple of the smaller factor that has already been tested.So, we`ll go through the range [2, sqrt (number)] to check if the number is divisible by any number or not. If it is a dividend, then it is not a prime number.Below is the implementation of this approach in PHP:
// PHP code to check if the number is prime or not
// function to check if the number is whether the number is primary or not function primeCheck ( $number ) { if ( $number == 1) return 0; for ( $i = 2; $i < = sqrt ( $number ); $i ++) { if ( $number % $i == 0) return 0; } return 1; }  
// Driver code $number = 31; $flag = primeCheck ( $number ); if ( $flag == 1) echo "Prime" ; else echo " Not Prime "?>
Output:
Prime  Time complexity: O (sqrt (n))                                       
             
                
Get Solution for free from DataCamp guru