Hướng dẫn php prime number generator

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

function primes($num){
//returns all prime numbers from 2 to $num as array
$primes = array(2);
$i = 3;
$end = $num; //alter this number to set upper limit
while($i <= $end){
while ($i <= $end){
$sqrt = ceil(sqrt($i));
foreach ($primes as $primus){
$p = $i % $primus; //gets remainder
if ($primus > $sqrt){
continue;
}
# echo $i . " divided by $primus = remainder " . $p . "
";
//uncomment above to show working out
if ($p == 0){
//if number divides by anything in the prime array (ie has 0 remainder) it will get bumped
break 2;
} //end if $p
} //end foreach primes
$primes[] = $i;
$primes = array_unique($primes);
$i+=2;
} //end while $i, adds number to primes array, otherwise...
$i+=2;
} //end while $i, *doesn't* add number to primes array
return $primes;
}
?>

Prime numbers are having only two factors, one is 1 and other one is the number itself.
These are the first 5 prime numbers 2, 3, 5, 7, 11
Prime numbers are divisible by exactly two natural numbers, 1 and the number itself.

Checking and listing all prime numbers in PHP by using loop and form to take user inputs

Checking numbers

Any number we can check if it is Prime number or not .
$n1=18;
$flag=0;
for($i=2;$i<=($n1/2); $i++){
	if($n1%$i == 0 ){
	$flag=1;
	break;
	}
}

if($flag==0){
	echo  "$n1 is a prime number " ;
}else{
	echo  "$n1 is NOT a prime number " ;
}	
Output
18 is NOT a prime number

Sticky form to take user input

We will ask user to enter any number in a sticky form and then display the number is prime number or not.
is a prime number
$n1=$_POST['n1']; // change this number 
echo "
"; $flag=0; for($i=2;$i<=($n1/2); $i++){ if($n1%$i == 0 ){ $flag=1; break; } } if($flag==0){ echo "$n1 is a prime number " ; }else{ echo "$n1 is NOT a prime number " ; }

Listing all prime numbers

We will loop through a range of numbers and check and list of all the prime numbers. ( All prime numbers less than 100 )
for($j=1;$j<=100;$j++){
$n1=$j;	
$flag=0;
for($i=2;$i<=($n1/2); $i++){
	if($n1%$i == 0 ){
	$flag=1;
	break;
	}
}

if($flag==0){
	echo  "$n1 , " ;
}	
}
Output is here
1 , 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43
 , 47 , 53 , 59 , 61 , 67 , 71 , 73 , 79 , 83 , 89 , 97 ,

Introduction to PHP Factorial of a number Sum of Digits of a number
Armstrong number Strong number
Basic Codes Check the string or number is Palindrome or not in PHP

Hướng dẫn php prime number generator



Hướng dẫn php prime number generator

plus2net.com