problem with loops while to calculate primary numbers who end with 9 - php

I would like to make a program which can calculate first 5000 primary numbers whos ends with 9 :
I tried this but it didn't work :
$div9 = [];
$x = 2;
while (count($div9) <= 5000) {
function findPrime($x)
{
for ($i = 2; $i < ($x / 2); $i++) {
$rest = $x % $i;
if ($rest == 0) {
break;
}
}
return $x;
}
$primeList[] = $x;
for ($j = 0; $j < count($primeList); $j++) {
$array = array_map('intval', str_split($primeList[$j]));
if (end($array[$j]) === 9) {
return $primeList[$j];
$div9[] = $primeList[$j];
}
}
$x++;
}
any hints please?

You should not define a function inside your while loop
This should help
function check_prime($num)
{
if ($num == 1)
return false;
for ($i = 2; $i <= $num/2; $i++)
{
if ($num % $i == 0)
return false;
}
return true;
}
$div9 = [];
$i = 0;
while(count($div9) < 5000) {
if($i%10 === 9 && check_prime($i)) {
$div9[] = $i;
}
$i++;
}

Another variation on the theme, the isPrime function was ported from Javascript cryptoJS library.
# Adapted from CryptoJS v3.1.2
function isPrime( $n=0 ){
$r=sqrt( $n );
for( $f=2; $f <= $r; $f++ ){
if( !( $n % $f ) )return false;
}
return true;
}
function isFactor($n,$f){
return $n % 10 == $f;
}
$limit=5000;
$primes=[];
$x=2;
$f=9;
while( count( $primes ) < $limit ){
if( isPrime( $x ) && isFactor( $x, $f ) )$primes[]=$x;
$x++;
}
printf('<pre>%s</pre>',print_r($primes,true));

Related

Display a complete number without scientific writing php [duplicate]

This question already has answers here:
Working with large numbers in PHP
(8 answers)
Closed 2 years ago.
Hello I would like to display in my code a full number to 20 decimal without scientific notation.
I think it's a memory problem in php.
can you help me ? thanks
function get($l, $c)
{
$value = 0;
if (0 <= $c && $c <= $l && $l < 5000) {
$tab = [];
for ($i = 0; $i <= $l; $i++) {
for ($j = 0; $j <= $c; $j++) {
if ($i == $j || $i - 1 <= 0 || $j <= 0) {
$tab[$i][$j] = 1;
$value = $tab[$i][$j];
} elseif ($i != $j) {
$tab[$i][$j] = ($tab[$i - 1][$j - 1]) + ($tab[$i - 1][$j]);
$value = $tab[$i][$j];
}
}
}
}
return $value;
}
echo get(67, 34); // found :1.422652073762E+19 , excpected:14226520737620288370
Have a look at BCMath functions:
function get($l, $c)
{
$value = 0;
if (0 <= $c && $c <= $l && $l < 5000) {
$tab = [];
for ($i = 0; $i <= $l; $i++) {
for ($j = 0; $j <= $c; $j++) {
if ($i == $j || $i - 1 <= 0 || $j <= 0) {
$tab[$i][$j] = 1;
$value = $tab[$i][$j];
} elseif ($i != $j) {
// magic happens here
$tab[$i][$j] = bcadd($tab[$i - 1][$j - 1], $tab[$i - 1][$j]);
$value = $tab[$i][$j];
}
}
}
}
return $value;
}
$result = get(67, 34);
var_dump($result == '14226520737620288370');
echo $result;
Output
bool(true)
14226520737620288370
Working example.
There is that : https://www.php.net/manual/en/function.number-format.php
You can print any number and choose number of decimals you want

print prime number [duplicate]

I need to find prime numbers with for loop or while loop
I wrote this but this is wrong
<?php
$i = 1;
while($i<5)
{
for($j=1; $j<=$i; $j++)
{
if ($j != 1 && $j != $i)
{
echo $i . "/" . $j . "=" . $i%$j . "<br />";
if ($i%$j != 0)
{
echo $i . "<br />";
}
}
}
echo "<br />";
$i += 1;
}
?>
Is there a way to divide a number with an array to find the remaining?
Here's a little function that I found: (http://icdif.com/computing/2011/09/15/check-number-prime-number/) Seemed to work for me!
function isPrime($num) {
//1 is not prime. See: http://en.wikipedia.org/wiki/Prime_number#Primality_of_one
if($num == 1)
return false;
//2 is prime (the only even number that is prime)
if($num == 2)
return true;
/**
* if the number is divisible by two, then it's not prime and it's no longer
* needed to check other even numbers
*/
if($num % 2 == 0) {
return false;
}
/**
* Checks the odd numbers. If any of them is a factor, then it returns false.
* The sqrt can be an aproximation, hence just for the sake of
* security, one rounds it to the next highest integer value.
*/
$ceil = ceil(sqrt($num));
for($i = 3; $i <= $ceil; $i = $i + 2) {
if($num % $i == 0)
return false;
}
return true;
}
You can use this PHP function gmp_nextprime()
Here is a one-liner I found a while back to check for primes. It uses tally marks (unary math) to determine:
function is_prime_via_preg_expanded($number) {
return !preg_match('/^1?$|^(11+?)\1+$/x', str_repeat('1', $number));
}
Check all numbers sequentially for primes:
$i=2; // start here (2 is the first prime)
while (1) { // neverending loop
if (is_prime_via_preg_expanded($i)) echo $i." <br />\n";
$i++;
}
To check only a range of numbers for primes like in the provided example:
$start = 2; // start here (2 is the first prime)
$end = 100;
$i=$start;
while ($i<=$end) {
if (is_prime_via_preg_expanded($i)) echo $i." <br />\n";
$i++;
}
This a basic implementation :
function prima($n){
for($i=1;$i<=$n;$i++){ //numbers to be checked as prime
$counter = 0;
for($j=1;$j<=$i;$j++){ //all divisible factors
if($i % $j==0){
$counter++;
}
}
//prime requires 2 rules ( divisible by 1 and divisible by itself)
if($counter==2){
print $i." is Prime <br/>";
}
}
}
prima(20); //find prime numbers from 1-20
This will output
2 is Prime
3 is Prime
5 is Prime
7 is Prime
11 is Prime
13 is Prime
17 is Prime
19 is Prime
Complete Logic step-by-step and visual analogy here : Here
Without math function:
function isPrimeNumber($i) {
$n = 2;
while ($n < $i) {
if ($i % $n) {
$n++;
continue;
}
return false;
}
return true;
}
I know it is too late, but I found that this solution is more elegant.
function isPrime($num)
{
if ($num < 2) {
return false;
}
for ($i = 2; $i <= $num / 2; $i++) {
if ($num % $i == 0) {
return false;
}
}
return true;
}
Anything who's sqrt() is false or any float value is prime number
This, I believe, is a quite efficient routine, which lists all the primes up to 1000.
It tests each number ($x) in order to see if it has any factors (other than itself and 1, of course).
Mathematically it is not necessary to test all lower numbers as possible factors, only lower primes up to the square root of $x. This is enabled by storing primes as they are found in an array (which I think is the strategy the OP was referring to).
As soon as the first prime factor is found, we know that $x is not prime, and so no further testing of that value of $x is needed and we can break out of the foreach loop.
$primes = array();
for ($x = 2; $x <= 1000; $x++) {
$xIsPrime = TRUE;
$sqrtX = sqrt($x);
foreach ($primes as $prime) if ($prime > $sqrtX || ((!($x % $prime)) && (!$xIsPrime = FALSE))) break;
if ($xIsPrime) echo ($primes[] = $x) . "<br>";
}
Sieve_of_Eratosthenes is simple and faster algorithm to find prime numbers.
function getPrimes($finish)
{
$number = 2;
$range = range($number,$finish);
$primes = array_combine($range,$range);
while($number*$number < $finish){
for($i=$number; $i<=$finish; $i+=$number){
if($i==$number){
continue;
}
unset($primes[$i]);
}
$number = next($primes);
}
return $primes;
}
<?php
$n = 11;
$o = $_POST["maxprime"];
echo 'The script calculated the next primenumbers:</br>';
echo '2, 3, 5, 7, ';
while (true) {
$t = 6;
while (true) {
if ($n % ($t - 1) == 0) {
break;
}
if ($n % ($t + 1) == 0) {
break;
}
if ($t > sqrt($n)) {
echo("$n, ");
break;
}
$t += 6;
}
if (($n + 1) % 6 == 0) {
$n += 2;
} else {
$n += 4;
}
if ($n > $o) {
break;
}
}
?>
http://www.primenumbergenerator.com/
Below programs is simple with two for loops and ignores 1 and self values in iteration. It will print the prime numbers,
function get_primenumbers($length) {
//Ignore 1
for($i = 2; $i <= $length; $i++){
$prime = true;
for($j = 2; $j <= $i; $j++){
//Ignore same number
if(($i != $j) && ($i % $j == 0)){
$prime = false;
break;
}
}
if(!$prime){
echo "$i is not prime <br />";
}else{
echo "$i is prime <br />";
}
}
}
$num = 25;
echo "Value Hardcored ".$num."<br>";
for($i=2; $i<$num; $i++)
{
if($num%$i==0)
{
$Loop = true;
echo "This is Composite Number";
break;
}
$Loop = false;
}
if($Loop == false)
{
echo "Prime Number";
}
i know this is coming kind of late, but hope it helps someone.
function prime_number_finder($range)
{
$total_count=0;//intitialize the range keeper
$i=1;//initialize the numbers to check
while ($total_count<=$range)
{
$count=0;//initialize prime number inner count
$k=$i;
while ($k!=0)
{
if(($i%$k)==0)
{
$count++;
}
$k--;
}
//condition to check if a number is prime
if($count==2 || $count==1)
{
echo $i."</br>";//output the prime number;
$total_count++;
$i++;
}
//number is not prime
if($count>2)
{
//$total_count++;
$i++;
}
}
}
//example
prime_number_finder(200);
$n = 7;
if ($n == 1) {
echo 'Not a Prime or Composite No.';
}
$set = 0;
for ($index = 2; $index <= $n/2; $index++) {
if ($n % $index === 0) {
$set = 1;
break;
}
}
if ($set) {
echo 'Composite';
} else {
echo 'Prime';
}
Find prime numbers between 1 and 10000, using a closure in array_filter():
$start = 2;
$step = 10000;
$stop = $start + $step;
$candidates = range($start, $stop);
for($num = 2; $num <= sqrt($stop); ++$num){
$candidates = array_filter($candidates,
function ($v) use (&$num){
return ($v % $num) != 0 || $v == $num ;
}
);
}
print_r($candidates);
Edit: 1 is not a prime number
The best way to check if a number is prime is to see if it is divisible by any prime number before it. Pi(x) is the one I keep seeing everywhere... You can see a bit more information on Prime Counting on wikipedia.
So the most efficient way I can think of at the moment is as follow:
class prime
{
public $primes = [ 2, 3, 5, 7 ];
public $not_prime = [ 1, 4, 6, 8, 9 ];
public function is_prime( int $n )
{
if ( $n <= 1 ) return false;
if ( in_array( $n, $this->primes ) ) return true;
if ( in_array( $n, $this->not_prime ) ) return false;
for( $i = 0; $i < count( array_slice( $this->primes, 0, $this->prime_count( $n ) ) ) || $i == $n; $i++ )
{
if ( $n % $this->primes[ $i ] == 0 ) return false;
}
return true;
}
public function build_primes_to( int $n )
{
for ( $i = end( $this->primes ) + 1; $i <= $n; $i++ )
{
if ( $this->is_prime( $i ) )
{
$this->primes[] = $i;
}
else
{
$this->not_prime[] = $i;
}
}
}
public function prime_count( $n )
{
$ln = log( $n );
if ( $ln == 0 ) return 1;
return intval( ceil( $n / $ln ) );
}
}
Which isn't actually very efficient, well, not when it comes to building the list of prime numbers... I've been working on a better way of building the list here, though it would be just as easy and far more efficient to find a list online and use that.
Usage of the above would be along the lines of:
$find_to = 1000;
$prime = new prime();
$prime->build_primes_to( $find_to );
print "<pre>";
for ( $i = 1; $i < $find_to; $i++ )
{
print "$i is " . ( !$prime->is_prime( $i ) ? "not " : "" ) . "prime\n";
}
I know this is coming a bit late, but here's a simple program to help you do just what you're asking for...
<?php
//Prime Function
function fn_prime($number) {
$i = 2; $result = TRUE;
while($i < $number) {
if(!($number%$i)) {
$result = FALSE;
}
$i++;
}
return $result;
}
//Declare integer variable...
$k = 0;
//Start Loop up to any number of your choice for e.g. 200
while($k < 200) {
if(fn_prime($k)) {
echo "$k is a prime number<br/>";
} else {
echo "$k is not a prime number!<br/>";
}
$k++;
}
?>
<?php
function prime_number($num){
for( $j = 2; $j <= $num; $j++ )
{
for( $k = 2; $k < $j; $k++ )
{
if( $j % $k == 0 )
{
break;
}
}
if( $k == $j )
echo "Prime Number : ".$j."<br>";
}
}
prime_number(23);
?>
Enchanced version of #Farkie answer made especially for checking primes in loops.
function isPrime_v2($num) {
static $knownPrimes=[3]; // array to save known primes
if($num == 1)
return false;
if($num == 2 || $num == 3) //added '3'
return true;
if($num % 2 == 0)
return false;
$ceil = ceil(sqrt($num)); //same purpose, good point from Farkie
// Check against known primes to shorten operations
// There is no sense to check agains numbers in between
foreach($knownPrimesas $prime){
if ($prime>$ceil)
break;
if($num===$prime)
return true;
if($num % $prime == 0)
return false;
}
/**
* end($knownPrimes) % 2 !==0 - mathematically guaranteed
* start with latest known prime
*/
for($i = end($knownPrimes)+2; $i <= $ceil; $i = $i + 2) {
if($num % $i == 0)
return false;
}
$knownPrimes[]=$num;
return true;
}
Benchmark with phpfiddle.org. V1 - Farkie answer, V2 - Enchanced version
V1 (1 to 5,000,000): divisions=330 929 171; primes=348 513; time=21.243s
V2 (1 to 5,000,000): divisions=114 291 299; primes=348 513; time=10.357s
NOTE! isPrime_v2 function is applicable ONLY in case of looping from 3. Otherwise saved $knownPrimes array will have insufficient history.
Here's another very simple but quiet effective approach:
function primes($n){
$prime = range(2 , $n);
foreach ($prime as $key => $value) {
for ($i=2; $i < $value ; $i++) {
if (is_int($value / $i)) {
unset($prime[$key]);
break;
}
}
}
foreach ($prime as $value) {
echo $value.'<br>';
}
}
primes(1000);
<?php
$limit=100;
$i=1;
outer:while($i<=$limit){
$j=2;
while($j<$i){
if($i%$j==0){
$i++;
goto outer;
}
$j++;
}
echo $i;
echo "<br/>";
$i++;
}
?>
<form method="post" action="">
<input type="number" name="demo" placeholder="Enter Any Number">
<button type="submit" name="aqeela" > Prime or composite </button>
</form>
<br>
<?php
if(isset($_POST['aqeela']))
{
$nu=$_POST['demo'];
if($nu==2)
{
echo "The Only Even Prime Number";
}
else
{
for($i=2; $i<$nu; $i++)
{
if($nu%$i==0)
{
echo "This is Composite Number";
break;
}
else
{
if($i==($nu-1))
{
echo "Prime number";
}
}
}
}
}

Is Generator supposed to be lazy?

I tried to calculate the nth prime number in PHP:
function is_prime($n) {
if ($n <= 1) {
return false;
} elseif ($n <= 3) {
return true;
} elseif (($n % 2 == 0) || ($n % 3 == 0)) {
return false;
}
$i = 5;
while ($i * $i <= $n) {
if (($n % $i == 0) || ($n % ($i + 2) == 0)) {
return false;
$i = $i + 6;
}
}
return true;
}
function prime_gen() {
for($x=0; $x< PHP_INT_MAX; $x++) {
if(is_prime($x)){
yield $x;
}
}
}
function nth_prime($n) {
for($i=0; $i<=$n; $i++) {
$ps = iterator_to_array(prime_gen());
}
return $ps[$n-1];
}
echo nth_prime(9);
I got Maximum execution time of 3 seconds exceeded error. Is generator supposed to be lazy? Shouldn't I write for($x=0; $x< PHP_INT_MAX; $x++)?
iterator_to_array iterates the entire generator until it is exhausted and gives you the result in an array. The generator is "lazy", but you're explicitly breaking that and are forcing the evaluation of the entire generator. Moreover, you're doing that in a loop. You pretty much just need to get rid of iterator_to_array. Better solution:
$nth = 0;
foreach (prime_gen() as $prime) {
if (++$nth >= $n) {
break;
}
}
return $prime;

Optimize substrings anagram compare algorithm

Im trying to solve one challenge where you have to check all string substrings are they anagrams. The condition is basically For S=abba, anagramic pairs are: {S[1,1],S[4,4]}, {S[1,2],S[3,4]}, {S[2,2],S[3,3]} and {S[1,3],S[2,4]}
Problem is that I have string with 100 chars and execution time should be below 9 secs. My time is around 50 secs... Below is my code, I will appreciate any advice - if you give me only directions or pseudo code it is even better.
$time1 = microtime(true);
$string = 'abdcasdabvdvafsgfdsvafdsafewsrgsdcasfsdfgxccafdsgccafsdgsdcascdsfsdfsdgfadasdgsdfawdascsdsasdasgsdfs';
$arr = [];
$len = strlen($string);
for ($i = 0; $i < strlen($string); $i++) {
if ($i === 0) {
for ($j = 1; $j <= $len - 1; $j++) {
$push = substr($string, $i, $j);
array_push($arr, $push);
}
} else {
for ($j = 1; $j <= $len - $i; $j++) {
$push = substr($string, $i, $j);
array_push($arr, $push);
}
}
}
$br = 0;
$arrLength = count($arr);
foreach ($arr as $key => $val) {
if ($key === count($arr) - 1) {
break;
}
for ($k = $key + 1; $k < $arrLength; $k++) {
if (is_anagram($val, $arr[$k]) === true) {
$br++;
}
}
}
echo $br."</br>";
function is_anagram($a, $b)
{
$result = (count_chars($a, 1) == count_chars($b, 1));
return $result;
}
$time2 = microtime(true);
echo "Script execution time: ".($time2-$time1);
Edit:
Hi again, today I had some time so I tried to optimize but couldnt crack this... This is my new code but I think it got worse. Any advanced suggestions ?
<?php
$string = 'abdcasdabvdvafsgfdsvafdsafewsrgsdcasfsdfgxccafdsgccafsdgsdcascdsfsdfsdgfadasdgsdfawdascsdsasdasgsdfs';
$arr = [];
$len = strlen($string);
for ($i = 0; $i < strlen($string); $i++) {
if ($i === 0) {
for ($j = 1; $j <= $len - 1; $j++) {
$push = substr($string, $i, $j);
array_push($arr, $push);
}
} else {
for ($j = 1; $j <= $len - $i; $j++) {
$push = substr($string, $i, $j);
array_push($arr, $push);
}
}
}
$br = 0;
$arrlen = count ($arr);
foreach ($arr as $key => $val) {
if (($key === $arrlen - 1)) {
break;
}
for ($k = $key + 1; $k < $arrlen; $k++) {
$result = stringsCompare($val,$arr[$k]);
if ($result === true)
{
$br++;
}
}
echo $br."\n";
}
function stringsCompare($a,$b)
{
$lenOne = strlen($a);
$lenTwo = strlen ($b);
if ($lenOne !== $lenTwo)
{
return false;
}
else {
$fail = 0;
if ($lenOne === 1) {
if ($a === $b) {
return true;
}
else
{
return false;
}
}
else
{
for ($x = 0; $x < $lenOne; $x++)
{
$position = strpos($b,$a[$x]);
if($position === false)
{
$fail = 1;
break;
}
else
{
$b[$position] = 0;
$fail = 0;
}
}
if ($fail === 1)
{
return false;
}
else
{
return true;
}
}
}
}
?>
You should think of another rule that all anagrams of a certain string can meet. For example, something about the number of occurrences of each character.

A formula to find prime numbers in a loop

I need to find prime numbers with for loop or while loop
I wrote this but this is wrong
<?php
$i = 1;
while($i<5)
{
for($j=1; $j<=$i; $j++)
{
if ($j != 1 && $j != $i)
{
echo $i . "/" . $j . "=" . $i%$j . "<br />";
if ($i%$j != 0)
{
echo $i . "<br />";
}
}
}
echo "<br />";
$i += 1;
}
?>
Is there a way to divide a number with an array to find the remaining?
Here's a little function that I found: (http://icdif.com/computing/2011/09/15/check-number-prime-number/) Seemed to work for me!
function isPrime($num) {
//1 is not prime. See: http://en.wikipedia.org/wiki/Prime_number#Primality_of_one
if($num == 1)
return false;
//2 is prime (the only even number that is prime)
if($num == 2)
return true;
/**
* if the number is divisible by two, then it's not prime and it's no longer
* needed to check other even numbers
*/
if($num % 2 == 0) {
return false;
}
/**
* Checks the odd numbers. If any of them is a factor, then it returns false.
* The sqrt can be an aproximation, hence just for the sake of
* security, one rounds it to the next highest integer value.
*/
$ceil = ceil(sqrt($num));
for($i = 3; $i <= $ceil; $i = $i + 2) {
if($num % $i == 0)
return false;
}
return true;
}
You can use this PHP function gmp_nextprime()
Here is a one-liner I found a while back to check for primes. It uses tally marks (unary math) to determine:
function is_prime_via_preg_expanded($number) {
return !preg_match('/^1?$|^(11+?)\1+$/x', str_repeat('1', $number));
}
Check all numbers sequentially for primes:
$i=2; // start here (2 is the first prime)
while (1) { // neverending loop
if (is_prime_via_preg_expanded($i)) echo $i." <br />\n";
$i++;
}
To check only a range of numbers for primes like in the provided example:
$start = 2; // start here (2 is the first prime)
$end = 100;
$i=$start;
while ($i<=$end) {
if (is_prime_via_preg_expanded($i)) echo $i." <br />\n";
$i++;
}
This a basic implementation :
function prima($n){
for($i=1;$i<=$n;$i++){ //numbers to be checked as prime
$counter = 0;
for($j=1;$j<=$i;$j++){ //all divisible factors
if($i % $j==0){
$counter++;
}
}
//prime requires 2 rules ( divisible by 1 and divisible by itself)
if($counter==2){
print $i." is Prime <br/>";
}
}
}
prima(20); //find prime numbers from 1-20
This will output
2 is Prime
3 is Prime
5 is Prime
7 is Prime
11 is Prime
13 is Prime
17 is Prime
19 is Prime
Complete Logic step-by-step and visual analogy here : Here
Without math function:
function isPrimeNumber($i) {
$n = 2;
while ($n < $i) {
if ($i % $n) {
$n++;
continue;
}
return false;
}
return true;
}
I know it is too late, but I found that this solution is more elegant.
function isPrime($num)
{
if ($num < 2) {
return false;
}
for ($i = 2; $i <= $num / 2; $i++) {
if ($num % $i == 0) {
return false;
}
}
return true;
}
Anything who's sqrt() is false or any float value is prime number
This, I believe, is a quite efficient routine, which lists all the primes up to 1000.
It tests each number ($x) in order to see if it has any factors (other than itself and 1, of course).
Mathematically it is not necessary to test all lower numbers as possible factors, only lower primes up to the square root of $x. This is enabled by storing primes as they are found in an array (which I think is the strategy the OP was referring to).
As soon as the first prime factor is found, we know that $x is not prime, and so no further testing of that value of $x is needed and we can break out of the foreach loop.
$primes = array();
for ($x = 2; $x <= 1000; $x++) {
$xIsPrime = TRUE;
$sqrtX = sqrt($x);
foreach ($primes as $prime) if ($prime > $sqrtX || ((!($x % $prime)) && (!$xIsPrime = FALSE))) break;
if ($xIsPrime) echo ($primes[] = $x) . "<br>";
}
Sieve_of_Eratosthenes is simple and faster algorithm to find prime numbers.
function getPrimes($finish)
{
$number = 2;
$range = range($number,$finish);
$primes = array_combine($range,$range);
while($number*$number < $finish){
for($i=$number; $i<=$finish; $i+=$number){
if($i==$number){
continue;
}
unset($primes[$i]);
}
$number = next($primes);
}
return $primes;
}
<?php
$n = 11;
$o = $_POST["maxprime"];
echo 'The script calculated the next primenumbers:</br>';
echo '2, 3, 5, 7, ';
while (true) {
$t = 6;
while (true) {
if ($n % ($t - 1) == 0) {
break;
}
if ($n % ($t + 1) == 0) {
break;
}
if ($t > sqrt($n)) {
echo("$n, ");
break;
}
$t += 6;
}
if (($n + 1) % 6 == 0) {
$n += 2;
} else {
$n += 4;
}
if ($n > $o) {
break;
}
}
?>
http://www.primenumbergenerator.com/
Below programs is simple with two for loops and ignores 1 and self values in iteration. It will print the prime numbers,
function get_primenumbers($length) {
//Ignore 1
for($i = 2; $i <= $length; $i++){
$prime = true;
for($j = 2; $j <= $i; $j++){
//Ignore same number
if(($i != $j) && ($i % $j == 0)){
$prime = false;
break;
}
}
if(!$prime){
echo "$i is not prime <br />";
}else{
echo "$i is prime <br />";
}
}
}
$num = 25;
echo "Value Hardcored ".$num."<br>";
for($i=2; $i<$num; $i++)
{
if($num%$i==0)
{
$Loop = true;
echo "This is Composite Number";
break;
}
$Loop = false;
}
if($Loop == false)
{
echo "Prime Number";
}
i know this is coming kind of late, but hope it helps someone.
function prime_number_finder($range)
{
$total_count=0;//intitialize the range keeper
$i=1;//initialize the numbers to check
while ($total_count<=$range)
{
$count=0;//initialize prime number inner count
$k=$i;
while ($k!=0)
{
if(($i%$k)==0)
{
$count++;
}
$k--;
}
//condition to check if a number is prime
if($count==2 || $count==1)
{
echo $i."</br>";//output the prime number;
$total_count++;
$i++;
}
//number is not prime
if($count>2)
{
//$total_count++;
$i++;
}
}
}
//example
prime_number_finder(200);
$n = 7;
if ($n == 1) {
echo 'Not a Prime or Composite No.';
}
$set = 0;
for ($index = 2; $index <= $n/2; $index++) {
if ($n % $index === 0) {
$set = 1;
break;
}
}
if ($set) {
echo 'Composite';
} else {
echo 'Prime';
}
Find prime numbers between 1 and 10000, using a closure in array_filter():
$start = 2;
$step = 10000;
$stop = $start + $step;
$candidates = range($start, $stop);
for($num = 2; $num <= sqrt($stop); ++$num){
$candidates = array_filter($candidates,
function ($v) use (&$num){
return ($v % $num) != 0 || $v == $num ;
}
);
}
print_r($candidates);
Edit: 1 is not a prime number
The best way to check if a number is prime is to see if it is divisible by any prime number before it. Pi(x) is the one I keep seeing everywhere... You can see a bit more information on Prime Counting on wikipedia.
So the most efficient way I can think of at the moment is as follow:
class prime
{
public $primes = [ 2, 3, 5, 7 ];
public $not_prime = [ 1, 4, 6, 8, 9 ];
public function is_prime( int $n )
{
if ( $n <= 1 ) return false;
if ( in_array( $n, $this->primes ) ) return true;
if ( in_array( $n, $this->not_prime ) ) return false;
for( $i = 0; $i < count( array_slice( $this->primes, 0, $this->prime_count( $n ) ) ) || $i == $n; $i++ )
{
if ( $n % $this->primes[ $i ] == 0 ) return false;
}
return true;
}
public function build_primes_to( int $n )
{
for ( $i = end( $this->primes ) + 1; $i <= $n; $i++ )
{
if ( $this->is_prime( $i ) )
{
$this->primes[] = $i;
}
else
{
$this->not_prime[] = $i;
}
}
}
public function prime_count( $n )
{
$ln = log( $n );
if ( $ln == 0 ) return 1;
return intval( ceil( $n / $ln ) );
}
}
Which isn't actually very efficient, well, not when it comes to building the list of prime numbers... I've been working on a better way of building the list here, though it would be just as easy and far more efficient to find a list online and use that.
Usage of the above would be along the lines of:
$find_to = 1000;
$prime = new prime();
$prime->build_primes_to( $find_to );
print "<pre>";
for ( $i = 1; $i < $find_to; $i++ )
{
print "$i is " . ( !$prime->is_prime( $i ) ? "not " : "" ) . "prime\n";
}
I know this is coming a bit late, but here's a simple program to help you do just what you're asking for...
<?php
//Prime Function
function fn_prime($number) {
$i = 2; $result = TRUE;
while($i < $number) {
if(!($number%$i)) {
$result = FALSE;
}
$i++;
}
return $result;
}
//Declare integer variable...
$k = 0;
//Start Loop up to any number of your choice for e.g. 200
while($k < 200) {
if(fn_prime($k)) {
echo "$k is a prime number<br/>";
} else {
echo "$k is not a prime number!<br/>";
}
$k++;
}
?>
<?php
function prime_number($num){
for( $j = 2; $j <= $num; $j++ )
{
for( $k = 2; $k < $j; $k++ )
{
if( $j % $k == 0 )
{
break;
}
}
if( $k == $j )
echo "Prime Number : ".$j."<br>";
}
}
prime_number(23);
?>
Enchanced version of #Farkie answer made especially for checking primes in loops.
function isPrime_v2($num) {
static $knownPrimes=[3]; // array to save known primes
if($num == 1)
return false;
if($num == 2 || $num == 3) //added '3'
return true;
if($num % 2 == 0)
return false;
$ceil = ceil(sqrt($num)); //same purpose, good point from Farkie
// Check against known primes to shorten operations
// There is no sense to check agains numbers in between
foreach($knownPrimesas $prime){
if ($prime>$ceil)
break;
if($num===$prime)
return true;
if($num % $prime == 0)
return false;
}
/**
* end($knownPrimes) % 2 !==0 - mathematically guaranteed
* start with latest known prime
*/
for($i = end($knownPrimes)+2; $i <= $ceil; $i = $i + 2) {
if($num % $i == 0)
return false;
}
$knownPrimes[]=$num;
return true;
}
Benchmark with phpfiddle.org. V1 - Farkie answer, V2 - Enchanced version
V1 (1 to 5,000,000): divisions=330 929 171; primes=348 513; time=21.243s
V2 (1 to 5,000,000): divisions=114 291 299; primes=348 513; time=10.357s
NOTE! isPrime_v2 function is applicable ONLY in case of looping from 3. Otherwise saved $knownPrimes array will have insufficient history.
Here's another very simple but quiet effective approach:
function primes($n){
$prime = range(2 , $n);
foreach ($prime as $key => $value) {
for ($i=2; $i < $value ; $i++) {
if (is_int($value / $i)) {
unset($prime[$key]);
break;
}
}
}
foreach ($prime as $value) {
echo $value.'<br>';
}
}
primes(1000);
<?php
$limit=100;
$i=1;
outer:while($i<=$limit){
$j=2;
while($j<$i){
if($i%$j==0){
$i++;
goto outer;
}
$j++;
}
echo $i;
echo "<br/>";
$i++;
}
?>
<form method="post" action="">
<input type="number" name="demo" placeholder="Enter Any Number">
<button type="submit" name="aqeela" > Prime or composite </button>
</form>
<br>
<?php
if(isset($_POST['aqeela']))
{
$nu=$_POST['demo'];
if($nu==2)
{
echo "The Only Even Prime Number";
}
else
{
for($i=2; $i<$nu; $i++)
{
if($nu%$i==0)
{
echo "This is Composite Number";
break;
}
else
{
if($i==($nu-1))
{
echo "Prime number";
}
}
}
}
}

Categories