如何在php中通过数组加速循环

How to speed up a loop through an array in php?

本文关键字:数组 加速 循环 php      更新时间:2023-10-16

我只是想将代码从c++移植到php,但是这个循环在c++中需要200ms,而在php中需要12秒

$answers2 = array_fill(0,28124*2+1,false);
$answers = SplFixedArray::fromArray($answers2);
for($i=0;$i< count($abundants);$i++){
    for($j=0;$j<=$i;$j++){
            $answers[$abundants[$i]+$abundants[$j]]=true;
    }
}

原始c++代码

#include <iostream>
#include <vector>
using namespace std;
int sum_of_divisors(int n){
  int prod=1;
  for(int k=2;k*k<=n;++k){
    int p=1;
    while(n%k==0){
      p=p*k+1;
      n/=k;
    }
    prod*=p;
  }
  if(n>1)
    prod*=1+n;
  return prod;
}
int main(){
  vector<int> abundant;
  for(int i=2;i<=28123;++i)
    if(sum_of_divisors(i)>2*i)
      abundant.push_back(i);
  bool sum_of_abundants[28123*2+1]={false};
  for(int i=0;i<abundant.size();++i)
    for(int j=0;j<=i;++j)
      sum_of_abundants[abundant[i]+abundant[j]]=true;
  int sum=0;
  for(int i=1;i<30000;++i)
    if(!sum_of_abundants[i])
      sum+=i;
  cout << sum << endl;
}

完整php代码

<?php
function is_abundant($num){
    $sum = 1;
    for($i = 2 ; $i <= sqrt($num) ; $i++){
        if($num % $i == 0){
            if($i!=$num/$i){
                $sum += $i + $num/$i;
            }
            else{
                $sum+= $i;
            }
            if($sum > $num){
                return true;
            }
        }
    }
}
$abundants = new SplFixedArray(6965);
//init
$index = 0;
for($j = 0 ;$j < 28124 ; $j++){
    if(is_abundant($j)){
        $abundants[$index] = $j;
        $index++;
    }
}
$answers2 = array_fill(0,28124*2+1,false);
$answers = SplFixedArray::fromArray($answers2);
$times = microtime(true);
for($i=0;$i< count($abundants);$i++){
    for($j=0;$j<=$i;$j++){
            $answers[$abundants[$i]+$abundants[$j]]=true;
    }
}
echo microtime(true) - $times."n";
$sum = 0;
for($i = 0 ;$i < 28124 ; $i++){
    if(!$answers[$i])
        $sum+=$i;
}
echo $sum."n";

我使用php版本5.5.9-1ubuntu4.11。你能帮我解决这个问题吗?

尝试执行以下操作。每次迭代都调用count方法,这会影响性能。只需使用一次,并将计数值赋给变量count

$count = count($abundants);
for($i=0 ; $i<$count ; $i++){
    for($j=0;$j<=$i;$j++){
            $answers[$abundants[$i]+$abundants[$j]]=true;
    }
}

您可以在这里找到循环优化的广泛列表

谢谢你