Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/229.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用于循环优化的PHP_Php_For Loop - Fatal编程技术网

用于循环优化的PHP

用于循环优化的PHP,php,for-loop,Php,For Loop,如果我有一个简单的案例, 例如: 数字7在数字1到100000000之间出现了多少次 这是我的代码: <?php $time_start = microtime(true); $counter = 0; $counter_num = 0; for ($i = 1; $i <= 1000000000; $i++) { if (substr_count($i, '7') > 0) { $counter = $counter + substr_count($i

如果我有一个简单的案例, 例如:

数字7在数字1到100000000之间出现了多少次

这是我的代码:

<?php
$time_start = microtime(true);
$counter = 0;
$counter_num = 0;
for ($i = 1; $i <= 1000000000; $i++) {
    if (substr_count($i, '7') > 0) {
        $counter = $counter + substr_count($i, '7');
        $counter_num++;
    }
    if ($i % 1000000 == 0) {
        echo 'Until ' . $i . "<br/>";
        echo "So Far: " . $counter;
        echo '<br/>';
        echo "Appears: " . $counter_num;
        echo '<br/>';
        $time_end = microtime(true);
        $execution_time = ($time_end - $time_start) / 60;
        echo '<b>Total Execution Time:</b> ' . $execution_time . ' Mins';
        echo '<br/>';
        echo '<hr/>';
    }
}
这意味着两个小时。。 如何优化这个循环?
我只是在寻找如何优化循环的答案,使用php、c#、javascript或任何编码语言都无关紧要。

这应该给你一个很好的指导:)


想想
00到999
,总共有多少个数字?1000每个数字有3位数字。因此总共有3000个数字。在一个系列中,所有数字的表示次数相等,总共使用10位。因此,使用了3000/10=300次7或6或5

我知道你们的实际需求不止这些。这显示了一个7被使用了多少个数字,但并没有显示到底有多少个7。但是,由于您的解决方案过于暴力,您可以从这里得到一个提示,并在此基础上进行构建


就像其他人说的那样,打两次substr\U计数没有任何意义。 我做了与rosscowar相同的事情,只是我没有更改for()并在exchange中添加中断,代码比他的代码快了0.5秒,尝试了10000000次(至少在我的机器上)


为什么要使用字符串操作来找到7,而不是通过StackExchange的数学论坛轻松找到的一些棘手的数学公式呢?不要使用循环是最好的方法。7在1和10之间出现多少次?1号和20号怎么样?1和100?当你看到图案时,你不需要循环。如果仍要使用循环
substr\u count($i,'7')
需要调用一次,而不是当前调用的两次。exusum是正确的。。还有别的办法吗?要进行优化?
$counter
需要包含7的总数,并且
$counter\u num
包含该总数中有多少个数字。您的
$counter
将始终保持不变。我忘记了,我已更改为$i,因此它是相同的,根本不需要$counter
Until 1000000000 So Far: 900000000 Appears: 612579511 Total Execution Time: 129.54485953252 Mins
<?php
    $from=0;
    $to=999999999;
    $numbers=$to-$from;
    echo ceil((strlen($to)*$numbers)/10);    // 900000000 times
?>
<?php
$time_start = microtime(true);
$counter_num = 0;
for ($i = 1; $i <= 10000000; $i++) {
    $counter_num += substr_count($i, '7');
    if ($i % 1000000 == 0) {
        echo 'Until ' . $i . "<br/>";
        echo "So Far: $i<br/>Appears: $counter_num<br/>";
        $execution_time = (microtime(true) - $time_start) / 60;
        echo '<b>Total Execution Time:</b> ' . $execution_time . ' Mins';
        echo '<br/>';
        echo '<hr/>';
    }
}