Jump to content

Need some help with prime numbers


fert

Recommended Posts

this is my code
[code]
<?php
$primes=array();
$cur=2;
$count=0;
$number=6;
while(1)
{
if($cur%2==0 && $cur%3==0 && $cur%4==0 && $cur%5==0 && $cur%6==0 && $cur%7==0 && $cur%8==0 && $cur%9==0)
{
$primes[$count]=$cur;
echo "{$primes[$count]}<br>";
$count++;

for($num=0;$num<count($primes);$num++)
{
$temp=$number/$primes[$count];
if(in_array($temp,$primes))
{
echo "{$temp} and {$primes[$count]}";
die();
}
}
}
                $cur++;
}
?>
[/code]
it's suppose to make a list of prime numbers, divide a number by a prime number in the list of primes and then see if the dividend is also in the prime list, but when i run it i get
[quote]
2520

Warning: Division by zero in /var/www/primes.php on line 16
5040

Warning: Division by zero in /var/www/primes.php on line 16

Warning: Division by zero in /var/www/primes.php on line 16
7560

Warning: Division by zero in /var/www/primes.php on line 16

Warning: Division by zero in /var/www/primes.php on line 16

Warning: Division by zero in /var/www/primes.php on line 16
10080

Warning: Division by zero in /var/www/primes.php on line 16

etc...
[/quote]
any ideas on how i can fix this code?
Link to comment
https://forums.phpfreaks.com/topic/34507-need-some-help-with-prime-numbers/
Share on other sites

I changed something and got a list of all the numbers you were echoing. I am not sure if this is what you waned.
[code]<?php
$primes=array();
$cur=2;
$count=0;
$number=6;
while(1)
{
if($cur%2==0 && $cur%3==0 && $cur%4==0 && $cur%5==0 && $cur%6==0 && $cur%7==0 && $cur%8==0 && $cur%9==0)
{
$primes[$count]=$cur;
echo "{$primes[$count]}<br>";
$count++;

for($num=0;$num<count($primes);$num++)
{
$temp=$number/$cur;
if(in_array($temp,$primes))
{
echo "{$temp} and {$primes[$count]}";
die();
}
}
}
                $cur++;
}
?>
[/code]

The loop is infinite, so after 30 seconds it stops.
Hey fert,

I think I found the problem.  Here:
[code]
<?php
//...
$temp=$number/$primes[$count];
//...
?>
[/code]

You are pointing to the data in the $primes array at index $count but you already incremented $count when you added $cur to the stack.  So $primes[$count] will always be null, hence the div by zero error.  Changing the code to:

[code]
<?php
//...
$temp=$number/$primes[$count - 1];
//...
?>
[/code]

Should solve the issue.

I'm a little curious as to how your method for finding primes works.  You check that every $cur mod x is congruent 0 where 2 <= x <= 9.  You're missing alot of primes using this method 3, 5, 7 to name a few.  I'm sure you have your reasons I'm just a bit curious as to what you're trying to do.

Best,

Patrick

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.