Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 201
Mohammad Masoudian Avatar asked May 26 '13 20:05

Mohammad Masoudian


People also ask

How do you find a prime number using a FOR loop?

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.

Is there a formula for finding prime numbers?

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.

How do you find a prime number in a loop python?

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.


2 Answers

$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";
 }
like image 176
kmt 9967 Avatar answered Oct 06 '22 04:10

kmt 9967


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++;
}
like image 32
Jeff Clayton Avatar answered Oct 06 '22 06:10

Jeff Clayton