如何在php中通过数组加速循环
How to speed up a loop through an array in php?
我只是想将代码从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;
}
}
您可以在这里找到循环优化的广泛列表
谢谢你
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '