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?
Program to Check Prime Number In the program, a for loop is iterated from i = 2 to i < n/2 . If n is perfectly divisible by i , n is not a prime number. In this case, flag is set to 1, and the loop is terminated using the break statement.
Two consecutive numbers which are natural numbers and prime numbers are 2 and 3. Apart from 2 and 3, every prime number can be written in the form of 6n + 1 or 6n – 1, where n is a natural number. Note: These both are the general formula to find the prime numbers.
To find a prime number in Python, you have to iterate the value from start to end using a for loop and for every number, if it is greater than 1, check if it divides n. If we find any other number which divides, print that value.
$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";
}
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++;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With