Find nearest sum of numbers in array to a given number - php

Say I have an array [10000,5000,1000,1000] and I would like to find the closest sum of numbers to a given number. Sorry for the bad explanation but here's an example:
Say I have an array [10000,5000,1000,1000] I want to find the closest numbers to, say 6000.
Then the method should return 5000 and 1000
another example : we want the closest to 14000 , so then he should return 10000 and 5000
here i've tried on php but it's something wrong when i put 6000 i should get 5000 and 1000
<?php
$arr = [10000,5000,1000,1000];
$x = 6000;
var_dump(eek($x,$arr));
function eek($x,$arr)
{
$index = [];
$counter = 0;
foreach($arr as $val)
{
if($counter + $val <= $x)
{
$counter += $val;
$index[] = $val;
}
elseif($counter + $val >= $x)
{
$counter += $val;
$index[] = $val;
break;
}
}
if($counter == $x)
{
return $index;
}
elseif($counter >= $x)
{
return $index;
}
else
{
return [];
}
}
?>
Anyone have solution about it ?

Here it is works with float and negative values:
$numbers = array(
10000,5000,1000,1000
);
$desiredSum = 6000;
$minDist = null;
$minDist_I = null;
// Iterate on every possible combination
$maxI = pow(2,sizeof($numbers));
for($i=0;$i<$maxI;$i++) {
if(!(($i+1) % 1000)) echo ".";
// Figure out which numbers to select in this
$sum = 0;
for($j=0;$j<sizeof($numbers);$j++) {
if($i & (1 << $j)) {
$sum += $numbers[$j];
}
}
$diff = abs($sum - $desiredSum);
if($minDist_I === null || $diff < $minDist) {
$minDist_I = $i;
$minDist = $diff;
}
if($diff == 0) break;
}
$chosen = array();
for($j=0;$j<sizeof($numbers);$j++) {
if($minDist_I & (1 << $j)) $chosen[] = $numbers[$j];
}
echo "\nThese numbers sum to " . array_sum($chosen) . " (closest to $desiredSum): ";
echo implode(", ", $chosen);
echo "\n";

Taking in count that the array is ordered from bigger to smaller values
Here is a solution, starting from yours
function eek($x,$arr)
{
$index = [];
$counter = 0;
foreach($arr as $key => $val) {
if($counter + $val < $x) {
$counter += $val;
$index[] = $val;
} else {
if (isset($arr[$key+1]) && (abs($counter + $arr[$key+1] -$x) < abs($counter + $val -$x))) {
continue;
} else {
$index[] = $val;
return $index;
}
}
}
return $index;
}

Related

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

Find a very first Fibonacci number which has 1000 digits

this is what i have coded to solve my problem it can produce a 10th digit number quickly, i have changed php.ini max-execution-time to 10000 still its not getting an answer in an hour . how can i run this code quickly/sppedly .
function fabNumber($n){
if($n==1 || $n==2) {
return 1;
}
return fabNumber($n-2) + fabNumber($n-1);
}
function count_digit($number){
return strlen($number);
}
$i = 1;
$count = 1;
while( $count != 1000){
$fab_number = fabNumber($i);
$count = count_digit($fab_number);
//var_dump($fab_number ,$count)."<br>";
++$i;
echo $fab_number . " index of ". $i ."<br>" ;
}
should i use GMP library
Edit 1:
function fabNumber($n){
if($n==1 || $n==2) {
return 1;
}
return gmp_strval( fabNumber($n-2) )+ gmp_strval(fabNumber($n-1) );
}
function count_digit($number){
return strlen($number);
}
$i = 1;
$count = 1;
while( $count != 100){
$fab_number =gmp_strval( fabNumber($i));
$count = count_digit($fab_number);
//var_dump($fab_number ,$count)."<br>";
++$i;
echo gmp_strval($fab_number) . " index of ". $i ."<br>" ;
}
#same slow progress
Something like:
function getFibonacci() {
$i = '0';
$k = '1'; //first fibonacci value
yield $k;
while(true) {
$k = gmp_add($i, $k);
$i = gmp_sub($k, $i);
yield $k;
}
}
foreach(getFibonacci() as $value) {
if (strlen($value) == 1000) {
break;
}
}
echo $value, PHP_EOL;
(PHP >= 5.5.0)
you can caching numbers to save time because in your version you recalculate all numbers at each iteration
$GLOBALS["fabTab"] = array();
function fabNumber($n){
if($n==1 || $n==2) {
return "1";
}
if (!isset($GLOBALS["fabTab"][$n])) {
$GLOBALS["fabTab"][$n] = bcadd(fabNumber($n-2), fabNumber($n-1));
}
return $GLOBALS["fabTab"][$n];
}
function count_digit($number){
return strlen($number);
}
$start = time();
$i = 1;
$count = 1;
while( $count != 1000) {
$fab_number = fabNumber($i);
$count = count_digit($fab_number);
//var_dump($fab_number ,$count)."<br>";
++$i;
}
echo "$fab_number<br/>index of ". $i ."<br>" ;
echo $count . " digits<br>" ;
echo (time() - $start) . " seconds<br>" ;

Sum of Prime numbers

I have the following code, to output all prime numbers from array. I would like to get the sum of the output in ex: 2+3+5 = 10, Any hint how to get that ?
$n = array(1,2,3,4,5,6);
function prime($n){
for($i=0;$i<= count($n);$i++){
$counter = 0;
for($j=1;$j<=$i;$j++){
if($i % $j==0){
$counter++;
}
}
if($counter == 2){
print $i."<br/>";
}
}
}
print prime($n);
Then this should work for you:
(Here i used $sum which i initialized before the foreach loop and then used the += operator to add the sum together)
<?php
$n = array(1,2,3,4,5,6);
function prime($n){
$sum = 0;
foreach($n as $k => $v) {
$counter = 0;
for($j = 1; $j <= $v; $j++) {
if($v % $j == 0)
$counter++;
}
if($counter == 2) {
echo $v."<br/>";
$sum += $v;
}
}
echo "Sum: " . $sum;
}
prime($n);
?>
Output:
2
3
5
Sum: 10
As #IMSoP commented above, one option is to compile the list of primes into a new array:
$m = [];
// looping code...
// If prime:
array_push( $m, $primeNumber );
Then, when you're done, you can do your printing mechanism:
print implode( "<br />", $m );
And then you can do your summing mechanism:
print "<p>Sum: " . array_sum( $m ) . "</p>";
The added benefit here is you can split out each piece of functionality into it's own function or method (which you should do to have a good design).
try this
<?php
define('N', 200);
function isPrime($num)
{
if ($num == 2 || $num == 3) { return 1; }
if (!($num%2) || $num<1) { return 0; }
for ($n = 3; $n <= $num/2; $n += 2) {
if (!($num%$n)) {
return 0;
}
}
return 1;
}
for ($i = 2; $i <= N; $i++) {
if (isPrime($i)) {
$sum += $i;
}
}
echo $sum;
You can try something like this:
function isPrime($n){
if($n == 1) return false;
if($n == 2) return true;
for($x = 2; $x <= sqrt($n); $x++){
if($n % $x == 0) return false;
}
return true;
}
$sum = 0;
$n = array(1,2,3,4,5,6);
foreach($n as $val){
if(isPrime($val)) {
echo $val . "<br />";
$sum += $val;
}
}
echo "Sum: " . $sum;
<?php
$num = 100;
for($j=2;$j<$num;$j++)
{
for($k=2;$k<$j;$k++)
{
if($j%$k==0)
{
break;
}
}
if($k==$j)
{
$prime_no[]=$j;
}
}
echo "<pre>";
print_r($prime_no);
echo "</pre>";
for($j=0;$j<count($prime_no);$j++)
{
$myprimeAdd = $prime_no[$j] + $prime_no[$j+1];
if(in_array($myprimeAdd,$prime_no))
{
echo "Resultant Prime No:-", $myprimeAdd;
echo nl2br("\n");
break;
}
}
?>

N random numbers that can duplicate after 2 elements

I want to generate 10 numbers with each ranging from (1 to 5) but can only duplicate after 2 elements
for example 5 3 1 4 2 5(can be duplicated here) 2 (cannot be duplicate here since it occur before 1 element) ...etc.
I have this code in php working but its performance is awful since it sometimes exceeds the maximum 30 seconds execution time.
<?php
function contain($prevItems, $number) {
if (count($prevItems) == 3)
{
array_shift($prevItems);
}
for ($k=0; $k<count($prevItems); $k++) {
if ($prevItems[$k] == $number)
return true;
}
return false;
}
$num[0] = rand(1,5);
$prevItems[0] = $num[0];
for ($i=1; $i<=10; $i++) {
$num[$i] = rand(1,5);
while (contain($prevItems, $num[$i])) {
$num[$i] = rand (1,5);
}
$prevItems[$i] = $num[$i]; //append into the array
}
print_r($num);
?>
Edit:
I have also tried this method, its performance is good but it duplicates elements
<?php
$evalAccurance = array();
$count = 0;
while ( $count < 11)
{
$random = rand(1, 5);
if (in_array($random, $evalAccurance))
{
$p = $random;
for ($k = $p ; $k <5; $k++)
{
$random = $random++;
if (in_array($random, $evalAccurance))
continue 1;
else break 1;
}
if (in_array($random, $evalAccurance))
{
for ($k = $p ; $k >0; $k--)
{
$random = $random--;
if (in_array($random, $evalAccurance))
continue 1;
else break 1;
}
}
}
$evalAccurance[] = $random;
if (count ($evalAccurance) == 4)
array_shift($evalAccurance);
print_r ($evalAccurance);
$count++;
}
?>
One way you could do this:
// pass to function current array of numbers
function randomNumber($ar){
// create a random number from 1 to 5
$num = rand(1,5);
// check backwards 3 elements for same number, if none found return it
if(!in_array($num, array_slice($ar, -3, 3, true))){
return $num;
} else {
// else recall function with same array of numbers
return randomNumber($ar);
}
}
$array = array();
// loop 10 numbers and call randomNumber with current set of results.
for($i=1; $i<=10; $i++){
$array[] = randomNumber($array);
}
print_r($array);
Using PHP SPLQueue:
$queue = new SplQueue();
$values = array(1, 2, 3, 4, 5);
$container = array();
for ($i = 0; $i < 10; $i++) {
$value = give_random($values, $queue);
$container[] = $value;
if ($queue->offsetExists(1) AND $queue->offsetExists(0)) {
$queue->dequeue();
}
$queue->enqueue($value);
}
function give_random(&$values, &$queue) {
$picked_value = $values[array_rand($values)];
if ($queue->offsetExists(1)) {
if ($picked_value == $queue->offsetGet(1)) {
$picked_value = give_random($values, $queue);
}
}
if ($queue->offsetExists(0)) {
if ($picked_value == $queue->offsetGet(0)) {
$picked_value = give_random($values, $queue);
}
}
return $picked_value;
}
print_r($container);
It could be neater, but you can figure what's going on.
Cheers.

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