What is a Prime Number ?

A number that is divisible only by itself and 1 (e.g. 2, 3, 5, 7, 11). All whole numbers above than 1 are either composite or prime.A prime is a whole number, and the only whole numbers that exactly divide into it, without a remainder, it is number divided by itself.

Example: 7 is a prime number. We can’t multiply 2, 3 or 4 together to make 7. (Only 1×7 works but we said to use other whole numbers.)

Example: 8 can be made by 2 × 4 so is NOT a prime number (it is a composite number).

Function

// Method 1
	function primenumber_1($number) {
		$i = 2;	
		for ($i = 2; $i <= $number-1; $i++) {
			if($number % $i == 0){ 
			 	return false;
				break;
			}
		}
		if($i==$number){
			return true;
		}
	}
	
// Method 2
	function primenumber_2($number) {
		$con1 = ($number == 2 || $number == 3 || $number == 5 || $number == 7) ? 1 : 0;
		$con2 = ($number % 2 && $number % 3 && $number % 5 && $number % 7) ? 1 : 0;
		$con3 = ($number != 0 && $number != 1) ? 1 : 0;
		return ($con1 || $con2 && $con3) ? 1 : 0;
	}
// Method 3 Similar to Method 2
	function primenumber_3($number){
		if($number == 2 || $number == 3 || $number == 5 || $number == 7 
		|| $number % 2 && $number % 3 && $number % 5 && $number % 7 
		&& $number != 0 && $number != 1){
			return true;
		}else{
			return false;
		} 
	}

Method 1

//Method 1
function primenumber_1($number) {
		$i = 2;	
		for ($i = 2; $i <= $number-1; $i++) {
			if($number % $i == 0){ 
			 	return false;
				break;
			}
		}
		if($i==$number){
			return true;
		}
	}
$number=7;
echo (primenumber_1($number))? "$number is Prime Number ": "$number is Not Prime";
//7 is Prime Number

Method 2

//Method 2
function primenumber_2($number) {
		$con1 = ($number == 2 || $number == 3 || $number == 5 || $number == 7) ? 1 : 0;
		// We Know 2 3 4 5 7 is Prime 
		$con2 = ($number % 2 && $number % 3 && $number % 5 && $number % 7) ? 1 : 0;
		// Every Prime Number Divided by it Self 
		// if number is divided with 2,3,5,7 we Get remainder 1 or greater its Prime Number
		// Else we Know its Divided itself so number is Not Prime
		$con3 = ($number != 0 && $number != 1) ? 1 : 0;
		// zero and One is Not Prime
		return ($con1 || $con2 && $con3) ? 1 : 0;
	}

	$number = 8;
	echo (primenumber_2($number))? "$number is Prime Number ": "$number is Not Prime";
// 8 is Not Prime

Demo

(Visited 106 times, 1 visits today)
Share with Friends :
Written by:

Leave a Reply

Your email address will not be published. Required fields are marked *