如何使用指定的接口为素数生成器编写代码。
答案 0 :(得分:1)
我认为这就是你所问的。
int isPrime(int i) {
int j;
if(i == 1 || i == 2)
return 1;
if(i % 2 == 0)
return 0;
for (j = 3; j < sqrt(n); j += 2)
if (i % j == 0)
return 0;
return 1;
}
void generator(int start, int end) {
int i;
if(start > end) {
int temp = start;
start = end;
end = start;
}
for (i = start; i<=end; i++)
if(isPrime(i))
printf("%d\n", i);
}
int main() {
generator(7900, 7920);
return 0;
}
答案 1 :(得分:0)
在这里,它确实在最后做了一件有趣的事情,但它确实有效。你可以在http://operationwalrus.com/primeval.php?x=1&y=100
看到它的实际效果<?
$x = $_GET['x'];
$y = $_GET['y'];
//$x and $y must be ordered acendingly
if ($x > $y) {
$temp = $x;
$x = $y;
$y = $temp;
}
$num = range($x, $y);
sort($num);
$arr = (findPrimeValues($num, $x, $y));
$arr = array_values(array_filter($arr));
for ($i=0;$i <= $y+1;$i++) {
$prnt = $arr[$i] . ', ';
str_replace(', ,', "",$prnt);
print_r($prnt);
}
function findPrimeValues($num, $x, $y) {
//1 is not prime. See: http://en.wikipedia.org/wiki/Prime_number#Primality_of_one
$pos = array_search(1, $num);
if (is_int($pos)) {
unset($num[$pos]);
}
/**
* if a number in the range is divisible by two and its not two, then it's
* not prime and it's removed from the array.
*/
for ($i=$x;$i <= $y;$i++) {
if (($i !== 2) && ($i % 2 == 0)) {
$pos = array_search($i, $num);
unset($num[$pos]);
}
}
/**
* Checks the odd numbers. If any of them is a factor, then it returns false.
* The sqrt can be an aproximation, hence just for the sake of
* security, one rounds it to the next highest integer value.
* $u is the number we are testing against.
*/
for ($u=$x;$u <= $y; $u++) {
for ($i = 3; $i <= ceil(sqrt($u)); $i = $u + 2) {
if($u % $i == 0) {
$pos = array_search($u, $num);
unset($num[$pos]);
}
}
}
return($num);
}