嗨,我正试图找出如何迭代整数,确定它们是否为素数,然后将素数放入一个数组,将非素数放入另一个数组。
我已经完成了检查素数的函数,为了简单起见,我将省略它。我只是似乎无法将值放入不同的数组中。这是我迄今为止所拥有的。
对此的任何见解都值得赞赏,我已经搜索了很多以前的问题,似乎还没有找到一个有效的答案,尽管这看起来很直接。
<?php
$start = 0;
$end = 1000;
$primes = array();
$nonPrimes = array();
for($i = $start; $i <= $end; $i++)
{
if(isPrime($i))
{
//add to the next available position in $primes array;
}
else
{
//add to the next available position in $nonPrimes array;
}
}
?>
array_push可能吗?
if(isPrime($i))
{
//add to the next available position in $primes array;
array_push($primes,$i);
}
else
{
//add to the next available position in $nonPrimes array;
array_push($nonPrimes,$i);
}
使用[]
运算符将元素添加到数组:
if (isPrime($i))
{
$primes[] = $i;
}
else
{
$nonPrimes[] = $i;
}
这将产生如下阵列:
$primes[2, 3, 5, 7, 11];
和
$nonPrimes[1, 4, 6, 8, 9, 10];