為了在基於 bash 的 php 中創建一個質數列表,以便在中斷後可以繼續執行,我使用了 fmod() 以及其他兩位用戶在此處 php 評論中提供的一些程式碼片段。
這將輸出
「質數;最後一個質數和目前質數之間的差」
所以功勞歸於他們。我只做了日誌文件輸出。
這將適用於 fmod 支援的任何最大值。只需輸入 $end 值。並 touch 建立日誌文件,然後使用 chmod 666 讓 php 可以訪問它。
<?php
function tailCustom($filepath, $lines = 1, $adaptive = true) {
$f = @fopen($filepath, "rb");
if ($f === false) return false;
if (!$adaptive) $buffer = 4096;
else $buffer = ($lines < 2 ? 64 : ($lines < 10 ? 512 : 4096));
fseek($f, -1, SEEK_END);
if (fread($f, 1) != "\n") $lines -= 1;
$output = '';
$chunk = '';
while (ftell($f) > 0 && $lines >= 0) {
$seek = min(ftell($f), $buffer);
fseek($f, -$seek, SEEK_CUR);
$output = ($chunk = fread($f, $seek)) . $output;
fseek($f, -mb_strlen($chunk, '8bit'), SEEK_CUR);
$lines -= substr_count($chunk, "\n");
}
while ($lines++ < 0) {
$output = substr($output, strpos($output, "\n") + 1);
}
fclose($f);
return trim($output);
}
function isPrime( $num )
{
for( $i = 2; $i*$i <= $num; $i++ )
if( !fmod($num,$i) )
return FALSE;
return TRUE;
}
$logfile = 'prim_save.log';
$lastline = explode(";", tailCustom($logfile));
$begin = ($lastline[0] +1);
$lastprime = $lastline[0];
$end = 999999999999999999999999999999999999;
$fp = fopen($logfile, 'a');
for($i = $begin; $i<$end; $i++)
{
if(isPrime($i) == TRUE)
{
$difference = $i - $lastprime;
fputs($fp,$i.';'.$difference.';'."\n");
$lastprime = $i;
}
}
fclose($fp);
?>