How can I make a conditional loop? - php

I have an array that contains different number of items every time. And I need to put this condition on the way of it:
"if the number of items are less than 2, then print nothihg, if the number of items are between 2 and 4, then print the first two items, if there are 5 items, then print all items".
Noted that the max number of array's items is 5.
$myarr = ["one", "two", "three"];
foreach($myarr as $item){
if( count($myarr) >= 2 && count($myarr) < 5 ){
echo $myarr[0].PHP_EOL;
echo $myarr[1];
} else if( count($myarr) == 5 ){
echo $myarr[0].PHP_EOL;
echo $myarr[1].PHP_EOL;
echo $myarr[2].PHP_EOL;
echo $myarr[3].PHP_EOL;
echo $myarr[4];
} else {
echo "nothing";
break;
}
}
As you can see, I've used echo $var[i] statically. How can make it shorter and dynamical?

You can use the following solution:
<?php
$myarr = ["one", "two", "three"];
$items_count = count($myarr);
if ($items_count < 2) {
echo "nothing";
} elseif ($items_count >= 2 && $items_count <= 4) {
echo implode(PHP_EOL, array_slice($myarr, 0, 2));
} else {
echo implode(PHP_EOL, $myarr);
}
demo: https://ideone.com/sG3Nm5
You don't need the foreach loop in this case. A simple list of conditions using count can do it.

There's many ways to skin this cat. These are my two cents:
Clean and readable version
$array = ["one", "two", "three"];
$count = count($array);
$iterations = 0;
if ($count < 2) {
echo 'nothing';
} else {
$iterations = $count <= 4 ? 2 : $count;
}
for ($i = 0; $i < $iterations; $i++) {
echo $array[$i] . PHP_EOL;
}
Demo: https://3v4l.org/CWHuj
More compact, harder to read and full of bad practices:
Note: This version was just for fun. Writing code like this in any other context should be illegal.
$array = ["one", "two", "three"];
$count = count($array);
if (!$iterations = $count < 2 ? 0 : ($count <= 4 ? 2 : $count)) echo "nothing";
for ($i = 0; $i < $iterations; $i++) echo $array[$i] . PHP_EOL;
Demo: https://3v4l.org/N1fnv

$myarr = ["one", "two", "three", "four", "five"];
$output = '';
foreach($myarr as $k=>$item){
if( count($myarr) >= 2 && count($myarr) < 5 && $k<2){
$output .= $item.PHP_EOL;
} else if( count($myarr) == 5 ){
$output .= $item.PHP_EOL;
} else if(count($myarr) <2) {
$output .= "nothing";
break;
}
}
echo $output;

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

How to Divide Array list in 3 Parts

<?php
$count=count($admissions);
$divide=$count/3;
$divide=round($divide);
foreach($admissions as $key => $row)
{
if(//First Part )
{
echo "Alpha";}
else if(//2nd Part )
{
echo "Beta";
}else
{
echo "Gamma";
}
}
?>
I have a dynamic array list and i want to divide it equally in 3 parts.
if Count of array is 30.
So i want to echo for first 10 record
echo "Alpha";
Second 10 Records
Echo "Beta";
3rd 10 Records
Echo "Gamma";
if array size is 60 then it will be divided into 20 parts each.
How can i echo the alpha, beta and gamma.
I thing your question is about if conditions. So you can use this code:
$count=count($admissions);
$divide=$count/3;
$divide=round($divide);
$i = 1;
foreach($admissions as $key => $row)
{
if($i > 0 && $i <= $divide)
{
echo "Alpha";
}
else if($i > $divide && $i <= ($divide*2))
{
echo "Beta";
}
else //equal else if($i > $divide*2 )
{
echo "Gamma";
}
$i++;
}
Try using a normal for loop :
For ($i = 0; $i < $count ; $i++){
echo "alpha";
}
For ($i = $count; $i < 2*$count ; $i++){
echo "beta";
}
For ($i = 2*$count; $i < 3*$count ; $i++){
echo "gamma";
}
Try this hope you are expecting this. According to the requirement which you specified in comments.
Try this code snippet here
<?php
ini_set('display_errors', 1);
$range=range(0,12);
$result=array_chunk($range, 4);
if(count($result[count($result)-1])!=4)
{
$temp=$result[count($result)-1];
unset($result[count($result)-1]);
$result[count($result)-1]=array_merge($result[count($result)-1],$temp);
}
print_r($result);
Let's have an array of three elements and play with the modulo:
<?php
$count=count($admissions);
$divide=$count/3;
$divide=round($divide);
$divisions = array(0 => array(), 1 => array(), 2 => array())
$modulo = 0;
foreach($admissions as $key => $row)
{
$divisions[($modulo + 1) % 3][$key] = $row;
}
This will do the partitioning you need.

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

how to find highest and second highest number in an array without using max function

I already have solution. But i think it will be more optimizable. So please provide me a solution for it. And remember that don't use predefined function of php. Like max() function.
i know there are so many ways to find it but i want best and better solution. Because my array contains more than 1 lakh records and it's taking lot of time. Or sometime site will be down.
My code :
<?php
$array = array('1', '15', '2','10',4);
echo "<pre>";
print_r($array);
echo "<pre>";
$max = 0;
$s_max=0;
for($i=0; $i<count($array); $i++)
{
$a = $array[$i];
$tmax = $max;
$ts_max = $s_max;
if($a > $tmax && $a > $ts_max)
{
$max = $a;
if($tmax > $ts_max) {
$s_max = $tmax;
} else {
$s_max = $ts_max;
}
} else if($tmax > $a && $tmax > $ts_max)
{
$max = $tmax;
if($a > $ts_max) {
$s_max = $a;
} else {
$s_max = $ts_max;
}
} else if($ts_max > $a && $ts_max > $tmax)
{
$max = $ts_max;
if($a > $tmax)
{
$s_max = $a;
} else {
$s_max = $tmax;
}
}
}
echo "Max=".$max;
echo "<br />";
echo "S_max=".$s_max;
echo "<br />";
?>
<?php
$array = array('200', '15','69','122','50','201');
$max_1 = $max_2 = 0;
for ($i=0; $i<count($array); $i++) {
if ($array[$i] > $max_1) {
$max_2 = $max_1;
$max_1 = $array[$i];
} else if ($array[$i] > $max_2 && $array[$i] != $max_2) {
$max_2 = $array[$i];
}
}
echo "Max=".$max_1;
echo "<br />";
echo "Smax 2=".$max_2;
See this solution.
<?php
$numbers = array_unique(array(1,15,2,10,4));
// rsort : sorts an array in reverse order (highest to lowest).
rsort($numbers);
echo 'Highest is -'.$numbers[0].', Second highest is -'.$numbers[1];
// O/P: Highest is -15, Second highest is -10
?>
I didn't check your solution, but in terms of complexity it's IMO optimal. If the array has no more structural information (like it's sorted) there's no way to skip entries. I.e. the best solution is in O(n) which your solution is.
This is a perfect and shortest code to find out the second largest value from the array. The below code will always return values in case the array contains only a value.
Example 1.
$arr = [5, 8, 1, 9, 24, 14, 36, 25, 78, 15, 37];
asort($arr);
$secondLargestVal = $arr[count($arr)-1];
//this will return 37
Example 2.
$arr = [5];
asort($arr);
$secondLargestVal = $arr[count($arr)-1];
//this will return 5
You can also use techniques in sorting like Bubble sort
function bubble_Sort($my_array )
{
do
{
$swapped = false;
for( $i = 0, $c = count( $my_array ) - 1; $i < $c; $i++ )
{
if( $my_array[$i] > $my_array[$i + 1] )
{
list( $my_array[$i + 1], $my_array[$i] ) =
array( $my_array[$i], $my_array[$i + 1] );
$swapped = true;
}
}
}
while( $swapped );
return $my_array;
}
$test_array = array(3, 0, 2, 5, -1, 4, 1);
echo "Original Array :\n";
echo implode(', ',$test_array );
echo "\nSorted Array\n:";
echo implode(', ',bubble_Sort($test_array)). PHP_EOL;
Original Array :
3, 0, 2, 5, -1, 4, 1
Sorted Array :
-1, 0, 1, 2, 3, 4, 5
Flow explanation
$array = array(80,250,30,40,90,10,50,60,50); // 250 2-times
$max = $max2 = 0;
foreach ($array as $key =>$val) {
if ($max < $val) {
$max2 = $max;
$max = $val;
} elseif ($max2 < $val && $max != $val) {
$max2 = $val;
}
}
echo "Highest Value is : " . $max . "<br/>"; //output: 250
echo "Second highest value is : " . $max2 . "<br/>"; //output: 90
The answer given by "Kanishka Panamaldeniya" is fine for highest value but will fail on second highest value i.e. if array has 2-similar highest value, then it will showing both Highest and second highest value same. I have sorted out it by adding one more level comparsion and it works fine.
$array = array(50,250,30,250,40,70,10,50); // 250 2-times
$max=$max2=0;
for ($i = 0; $i < count($array); $i++) {
if ($array[$i] > $max) {
$max2 = $max;
$max = $array[$i];
} else if (($array[$i] > $max2) && ($array[$i] != $max)) {
$max2 = $array[$i];
}
}
echo "Highest Value is : " . $max . "<br/>"; //output : 250
echo "Second highest value is : " . $max2 . "<br/>"; //output : 70
This code will return second max value from array
$array = array(80,250,30,250,40,90,10,50,60,50); // 250 2-times
$max=$max2=0;
for ($i = 0; $i < count($array); $i++) {
if($i == 0) {
$max2 = $array[$i];
}
if($array[$i] > $max) {
$max = $array[$i];
}
if($max > $array[$i] && $array[$i] > $max2) {
$max2 = $array[$i];
}
}
echo "Highest Value is : " . $max . "<br/>"; //output : 250
echo "Second highest value is : " . $max2 . "<br/>"; //output : 90
Two way find the second highest salary
1. Sort the data in Descending order
2. get array first value
3. Check the condition already comments
$array = [2,3,6,11,17,14,19];
$max = $array[0];
$count = count($array);
for($i=0; $i<$count;$i++)
{
for($j=$i+1;$j<$count;$j++)
{
if($array[$i] < $array[$j])
{
$temp = $array[$i];
$array[$i] = $array[$j];
$array[$j] = $temp;
}
}
}
First Method
//echo $array[1]; // Second highest value
$second ='';
for($k=0;$k<2;$k++)
{
if($array[$k] >$max)
{
$second = $array[$k];
}
}
echo $second; // Second method
Without using MAX function. Here.
$arr = [3,4,-5,-3,1,0,4,4,4];
rsort($arr); // SORT ARRAY IN DESCENDING ORDER
$largest = $arr[0]; // IN DESCENDING ORDER THE LARGEST ELEMENT IS ALWAYS THE FIRST ELEMENT
$secondLargest = 0;
foreach($arr as $val){
$secondLargest = $val; // KEEP UPDATING THE VARIABLE WITH THE VALUE UNTIL IT RECEIVES THE FIRST ELEMENT WHICH IS DIFFERENT FROM THE LARGEST VALUE
if($val != $arr[0]){
break; // BREAK OUT OF THE LOOP AS SOON AS THE VALUE IS DIFFERENT THAN THE LARGEST ELEMENT
}
}
echo $secondLargest;

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