Is Generator supposed to be lazy? - php

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;

Related

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

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));

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";
}
}
}
}
}

PHP - check if number is prime

I'm trying to create a function which checks whether the number is prime or not. BUT I want this function to echo to the user 'prime' or 'NOT prime' - and that's where my problem starts.
Let me show you my code:
class IsPrime
{
function check($num)
{
for ($i = 2; $i < $num; $i++)
{
if ($num % $i == 0)
{
echo 'NOT prime';
break;
}
}
echo 'Prime';
}
}
$x = new IsPrime();
$x->check(4);
The problem is that when I put any prime number - it works correctly, but when I put any not prime number - it also echos second echo, sth like this: 'NOT prime prime'.
How can I make it echo only the right answer ?
in 54 59 bytes:
function is_prime($n){for($i=$n;--$i&&$n%$i;);return$i==1;}
loops $i down from $n-1 until it finds a divisor of $n; $n is prime if that divisor is 1.
add 10 bytes for much better performance:
function is_prime($n){for($i=$n**.5|1;$i&&$n%$i--;);return!$i&&$n>1;}
loops $i from (approx.) sqrt($n) to 1 looking for a divisor with a post-decrement on $i.
If the divisor is 1, $i will be 0 at the end, and !$i gives true.
This solition uses a trick: For $n=2 or 3, $i will be initialized to 1 → loop exits in first iteration. For larger even square roots ($n**.5|0), |1 serves as +1. For odd square roots, +1 is not needed because: if $n is divisible by root+1, it is also divisible by 2. Unfortunately, this can cost a lot of iterations; so you better
add another 7 bytes for even better performance:
function is_prime($n){for($i=~-$n**.5|0;$i&&$n%$i--;);return!$i&$n>2|$n==2;}
$n=2 needs a special case here: inital $i=2 divides $n=2 → final $i=1 → returns false.
Adding 1 to $n instead of the square root is enough to avoid failures; but:
I did not count the iterations but only tested time consumption; and that only in TiO instead of a controlled environment. The difference between the last two versions was smaller than the deviation between several runs.
Significant test results may be added later.
This could be a long procedure if the number is really a prime number. There is a shorter procedure as well.
We need not run the for loop upto the number itself. Instead, we can run it upto the Highest Integer less than or equal to the square root of the number.
class IsPrime
{
function check($num)
{
$bCheck = True;
$highestIntegralSquareRoot = floor(sqrt($num));
for ($i = 2; $i <= $highestIntegralSquareRoot; $i++)
{
if ($num % $i == 0)
{
$bCheck = False;
break;
}
}
if $bCheck
echo 'Prime';
else
echo 'NOT prime';
}
}
$x = new IsPrime();
$x->check(97);
Now, in the above, if we check check whether 97 is prime or not (actually, it is), then the loop need not run from 2 to 97, but only from 2 to 9. (Square root of 97 is 9.8488578018, and highest integer less than or equal to that is 9. Similarly, we can check for number 121 (this is not a prime number, as it is divisible by 11). The limit will be increased from 2 to 11 in a similar matter. And so on.
Actually, we need to check the divisibility of the number by the smaller prime numbers in the vicinity, but that would be more complex.
Hope this helps.
As many answer pointed out, your logic code has a problem: when you get i such that num % i == 0, you print "NOT prime" and quit the loop, after that, you still print "Prime". Some guys moved echo "Prime" in if-else, it is still wrong. One way to approach, for example,
class IsPrime
{
function check($num)
{
$bCheck = True;
for ($i = 2; $i < $num; $i++)
{
if ($num % $i == 0)
{
$bCheck = False;
break;
}
}
if $bCheck
echo 'Prime';
else
echo 'NOT prime';
}
}
$x = new IsPrime();
$x->check(4);
<?php
function primeCheck($num)
{
if ($num == 1)
return false;
for ($i = 2; $i <= $num/2; $i++)
{
if ($num % $i == 0)
{
return false;
}
}
return true;
}
$primeNumber = primeCheck(17);
if ($primeNumber == true)
{
echo "Is Prime";
}
else
{
echo "Is Not Prime";
}
?>
The break is only breaking the for loop,
use return; instead. it will exit the function
Just use return:
class IsPrime
{
function check($num)
{
for ($i = 2; $i < $num; $i++)
{
if ($num % $i == 0)
{
echo 'NOT prime';
return; // that you need
}
}
echo 'Prime';
}
}
$x = new IsPrime();
$x->check(4);
if/else notation
return notation
You can find prime numbers and non prime numbers from 1 to your limit and its count.
public function prime_checker($count){
$counter=0;
$no_prime=0;
for($i=2 ; $i<=$count; $i++ ){
for($j=2 ; $j<$i ; $j++ ){
if($i % $j == 0){
echo $i.'is not prime<br/>';
$no_prime=$i;
break;
}
}
if($i != $no_prime){
$prime_numbers[$counter]=$i;
$counter=$counter+1;
}
}
echo '<br/>'.$counter.'prime numbers<br/><br/>';
for($i=0 ; $i<$counter ; $i++ ){
echo $prime_numbers[$i].' is prime<br/>';
}
}
You can check number is prime or not & without using loop with this function:
function is_prime($p) {
$r1 = $p%2;
$r2 = $p%3;
$r3 = $p%5;
return ($p > 1) && (($r1 >= 1) && ($r2 >= 1) && ($r3 >= 1)) || in_array($p, [2,3,5]);
}
Please Check this
class IsPrime
{
function check($num)
{
for ($i = 2; $i < $num; $i++)
{
if ($num % $i == 0)
{
return 'NOT prime';
}
}
return 'Prime';
}
}
$x = new IsPrime();
$result = $x->check(4);
echo $result;
try this
class IsPrime
{
function check($num)
{
for ($i = 2; $i < $num; $i++)
{
if ($num % $i == 0)
{
echo 'NOT prime';
break;
}
else
{
echo 'Prime';
}
}
//echo 'Prime';
}
}
$x = new IsPrime();
$x->check(3);
Put else part otherwise it will always return Prime
for ($i = 2; $i < $num; $i++)
{
if ($num % $i == 0)
{
echo 'NOT prime';
break;
}
echo 'Prime';
}
You can print "Prime" as a return to the function to ensure nothing is printed during the function except for the condition for "NOT prime".
class IsPrime
{
function check($num)
{
for ($i = 2; $i < $num; $i++)
{
if ($num % $i == 0)
{
echo 'NOT prime';
break;
}
}
return "Prime";
}
}
$x = new IsPrime();
echo $x->check(4);
$num = ceil(sqrt($num));
$is_prime = true;
for($j=3; $j<=$num; $j=$j+2){
if($i%$j == 0){
$is_prime = false;
break;
}
}
if($is_prime){
echo "No is Prime";
}
Note: Start loop from 2 as it is the only even prime no. Increment with 2 as no even no is a prime no.
=> Code for finding all prime no in range (2-100)
$limit = 100; $arr = array(2);
for($i=3; $i<=$limit; $i=$i+2){
$num = ceil(sqrt($i));
$is_prime = true;
for($j=3; $j<=$num; $j=$j+2){
if($i%$j == 0){
$is_prime = false;
break;
}
}
if($is_prime){
$arr[] = $i;
}
}
I made a similar one where a user types in a number and PHP checks if the number is prime or not.
HTML
<p>See if your number is a prime number</p>
<form>
<input type='number' name='number'>
<input type='submit' value='Check!'>
</form>
PHP
if ($_GET) {
$i = 2;
$isPrime = true;
while ($i < $_GET['number']) {
if ($_GET['number'] % $i == 0){
// Number is NOT prime
$isPrime = false;
}
$i++;
}
if ($isPrime){
echo '<p>'.$i.' is a prime number!';
} else {
echo '<p>'.$i.' is NOT a prime number';
}
}
Hopefully this works for you.
First, don't make a mistake here:
for ($i = 2; $i < $num; $i++)
and then:
if ($num % $i == 0) return false;
2 % 2 equals 0 and then 2 will result as NOT prime.
Next, you don't have to check even numbers, so after you check if $num == 2, better performance is:
for ($i = 3; $i < $num/2; $i += 2)
Notice $num/2 - you don't have to check beyond that point.
And even better is:
for ($i = 3; $i*$i <= $num; $i += 2)
This is because when you check for division with 2 and 3 all other NON prime numbers are product of two (or more) prime numbers (e.g. 49 = 7*7 or 55 = 5*11). In the worst case scenario your $i pointer would reach a square root of $num (like in 49 = 7*7). That's why you check until $i*$i <= $num.
PHP 4
You can do enough random checks ($i=20) to bring the false positive probability very low.
/*
The Rabin/Miller Algorithm.
*/
function is_prime($n, $i = 10)
{
if (($n == 1) == ($n & 1)) return $n == 2;
if ($n < 51529) // will not be repeated 7 times (deletable condition)
return ($n & 1) & (($n < 6) * 42 + 0x208A2882) >> $n % 30 && ($n < 49 || ($n % 7 && $n % 11 && $n % 13 && $n % 17 && $n % 19 && $n % 23 && $n % 29 && $n % 31 && $n % 37 && ($n < 1369 || ($n % 41 && $n % 43 && $n % 47 && $n % 53 && $n % 59 && $n % 61 && $n % 67 && $n % 71 && $n % 73 && ( $n < 6241 || ($n % 79 && $n % 83 && $n % 89 && $n % 97 && $n % 101 && $n % 103 && $n % 107 && $n % 109 && $n % 113 && ( $n < 16129 || ($n % 127 && $n % 131 && $n % 137 && $n % 139 && $n % 149 && $n % 151 && $n % 157 && $n % 163 && $n % 167 && ( $n < 29929 || ($n % 173 && $n % 179 && $n % 181 && $n % 191 && $n % 193 && $n % 197 && $n % 199 && $n % 211 && $n % 223))))))))));
for ($a = $c = $n - 1, $d = $c - 1, $b = 0; !($a & 1); $a >>= 1, ++$b) ;
for (; $i--;) {
do for ($e = $f = mt_rand(1, $d), $g = $n; ($e %= $g) && ($g %= $e);) ;
while ($e > 1 && $g > 1);
for ($e = $g = 1; $g <= $a; $g <<= 1) ;
for (; $g >>= 1; $e = ($e * $e) % $n, $g & $a && ($e = ($f * $e) % $n)) ;
if ($e == 1) continue;
for ($r = $b; $r-- ; $e = ($e * $e) % $n)
if ($e == $c) continue 2;
return 0;
}
return 1;
}
echo is_prime(2147483647); // 1
echo is_prime(PHP_MAJOR_VERSION); // You Know
This PHP4 variant of the Fermat test has a polynomial runtime in log($n).
Just use it for small numbers, when $n < 2147483647, otherwise it's gmp_prob_prime.
Thank You.
function is_prime($number)
{
return (bool) !preg_match('/^1?$|^(11+?)\1+$/x', str_repeat('1', $number));
}
Entire program is correct . But only you should do replace break with exit function .because break only used to exit loop which are enclosed with curly braces {} and exit are used to stop the execution of an entire script.
class IsPrime
{
function check($num)
{
for ($i = 2; $i < $num; $i++)
{
if ($num % $i == 0)
{
echo 'NOT prime';
break;
}
}
echo 'Prime';
}
}
$x = new IsPrime();
$x->check(4);
That is my solution. If you put the condition in the loop and break after it, it's never going to finish with the check.
$num = rand ( 1, 1000 );
$notPri = null;
for($check = 2; $check < $num; $check ++) {
if ($num % $check == 0) {
$notPri ++;
}
}
if ($neEpri == 0) {
echo $num . "<br>Prime!";
} else {
echo $num . "<br>Not a prime!";
}

I need to find all amicable numbers up to a certain number

Here is my code:
$n = 300;
$set = 0;
$set2 = 0;
for($i = 1; $i<$n; $i++)
{
for($j = 1; $j <$i; $j++)
{
$qol = $i % $j;
if($qol == 0)
{
$set += $j;
}
}
for($s=1; $s<$set; $s++)
{
$qol2 = $set % $s;
if($s == 0)
{
$set2 += $s;
}
}
if($set2 == $i)
{
echo "$set and $i are amicable numbers</br>";
}
}
I do not know what the heck the problem is!
FYI: 220 and 284 are an example of amicable numbers. The sum of the proper divisors of one number are equal to other number and vice versa (wiki).
I am having troubles following your logic. In your code how would $set2 == $i ever be true? Seems to me that $i would always be greater.
I would do it the following way:
First make a separate function that finds the sums of the proper divisors:
// Function to output sum of proper divisors of $num
function sumDiv($num) {
// Return 0 if $num is 1 or less
if ($num <= 1) {
return 0;
}
$result = 1; // All nums divide by 1
$sqrt = sqrt($num);
// Add divisors to result
for ($i = 2; $i < $sqrt; $i++) {
if ($num % $i == 0) {
$result += $i + $num / $i;
}
}
// If perfect square add squareroot to result
if (floor($sqrt) == $sqrt) {
$result += $sqrt;
}
return $result;
}
Next check each iteration for a match:
$n = 1500;
for ($i = 1; $i < $n; $i++) {
// Get sum of proper devisors of $i, and sum of div. of result.
$currentDivs = sumDiv($i);
$resultDivs = sumDiv($currentDivs);
// Check for a match with sums not equal to each other.
if ($i == $resultDivs && $currentDivs != $resultDivs) {
echo "$i and $currentDivs are amicable numbers<br>";
}
}
Here a functioning phpfiddle.
Warning: Large numbers will take very long to process!

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