2015-08-15 18 views
1

我只想端口从C++到PHP代码,但这个循环需要用C 200毫秒+ +,但在PHP12秒如何加快通过PHP中的数组循环?

$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。 你能帮我解决这个问题吗?

回答

1

请尝试执行以下操作。您在每次迭代中都会调用count方法,这是性能问题。只要使用一次,计数值分配给一个变量count

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

你会发现循环优化的广泛的名单here

谢谢:)

+0

谢谢,但仍然有同样的问题! – Daniyal

+0

另一个原因是PHP的动态输入。这里,变量类型在运行时进行检查,而不是编译时间,这会影响PHP的运行时性能。因此,像C++这样的静态类型语言在运行时会显着加快速度,尽管它们通常需要提前编译。 –

+2

'++ $ i'也比'$ i ++'快大约25%,因为在后者中,变量在递增之前被临时缓存。用于长时间迭代。 – jonbaldie