Reputation: 978
I'm trying to verify the 3x + 1 problem
, by running a PHP script online and evaluating all numbers.
I have an infinite loop running, but the server stops my loop when the value reaches about 35,000.
I'm guessing the termination is caused when my HTTP connection resets and the server is no longer serving my request.
I want to have it run as long as it can, eating up the server's resources if it wants to. How do I do it? Cronjobs?
Here's the script, the "End" is never printed.
class Collatz_Verify
{
public function Collatz_Verify()
{
// open output file
$file = 'verified_nums.txt';
$outFile = fopen($this->NUMBERS_FILENAME, 'a');
}
public function verify()
{
$num = 0;
while(1)
{
$num += 1;
# call collatz!!
if($this->collatz($num) == 1)
fwrite($this->outFile, $num);
}
print "ah, crap! End!";
}
public function collatz($num)
{
if ($num == 1)
return 1;
if (($num % 2) == 0)
return $this->collatz($num/2);
else
return $this->collatz((3*$num) + 1);
}
}
// Fire away!
$ver = new Collatz_Verify();
$ver->verify();
?>
Upvotes: 1
Views: 357
Reputation: 9874
There are two possible reasons for PHP to stop executing your loop.
The first is that the execution time limit is reached.
The second is that the maximum nesting level is reached (due to recursion in collatz()
).
The maximum nesting level is 100 (I'm not aware of ways to change that). The default execution time limit is 30 seconds. You can increase that, as the other answers show.
To find out what the reason is that your script stops, you should set display errors to on and/or check the error log of the web server. Also you could check the output file and start with the last successful number. So if the last number in the output file is 34998 then change the line $num = 0;
into $num = 34998;
.
Upvotes: 1
Reputation: 4022
The end never prints, because you are in a while(1)
loop and thus the statement afterwards will never be reached.
Your script is probably terminated because of your settings in php.ini
for the variable max_execution_time
Edit: Try to use the function set_time_limit()
https://www.php.net/manual/en/function.set-time-limit.php to be able to increase the time in your script.
Upvotes: 2
Reputation: 59987
In the PHP.ini
file there are limits on time for the script to execute/memory that the script can use.
See http://php.net/manual/en/info.configuration.php for full details
Upvotes: 0
Reputation: 583
You could run it from command line... you'll eventually stop due to lack of resources though.
Running from command line will prevent you from having to do the ini_set mentioned just before my post. (see: http://www.php.net/manual/en/info.configuration.php#ini.max-execution-time)
Upvotes: 2
Reputation: 737
php has a max_execution_time limit, If you want it to run for longer, you could try ini_set('max_execution_time' ,100 ); //Replace 100 with how many seconds you want it to be able to run
Upvotes: 1