Page 1 of 1

PHP Primary Number

Posted: Tue Sep 25, 2007 3:45 am
by cutlass
feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


Need help in my code.   I need to find or place a looping statement in here to test all division possilibilies.  I'm not sure in where to put the looping statement at.  Thanks.

I have a webpage where you put in the number you test the possibilities, but just need help in put the looping statement in.

Code: Select all

<?php 
// is_prime(number) checks if a number is a prime number or not 
function is_prime($i) 
{ 
if($i % 2 != 1) return false; 
$d = 3; 
$x = sqrt($i); 
while ($i % $d != 0 && $d < $x) $d += 2; 
return (($i % $d == 0 && $i != $d) * 1) == 0 ? true : false; 
} 


// show all prime numbers between $start and $end 
$start = 0; 
$end = 999; 
for($i = $start; $i <= $end; $i++) 
{ 
if(is_prime($i)) 
{ 
echo ' 
'.$i.' '; 
} 
   } 
?>

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Tue Sep 25, 2007 3:54 am
by aceconcepts
You are already using a FOR loop!

Posted: Tue Sep 25, 2007 4:12 am
by devendra-m
feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


I think you are doing extravagant calculation.I have very easy solution.  If following condition satisfies then the given number is prime.

     2^(k-1) % k = 1
   
    where k=input number

  the algorithm is

Code: Select all

function checkPrime()
{
   $min=1;
   $max=100;
    for($i=$min;$i<=$max;$i++)
    {
         if((pow(2,($i-1))%$i)==1)
              print("prime number is ".$i);
       
     }
}

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]