【发布时间】:2017-10-17 21:33:50
【问题描述】:
我创建的这段代码遍历数字 1-100 并消除非素数,即留下 2、3、5、..97。但是,它包含 2 个用于排序算法的 for 循环,因此速度很慢。最重要的是,数字“0”保留在被淘汰数字的位置。
我的问题是,我怎样才能使这个程序达到 O(n) 的性能,我怎样才能将 nums[] 中的素数复制到另一个数组中,以便它们按顺序排列?
#include <stdio.h>
#define MAX 100
int main ()
{
int nums[MAX];
int i,j;
for (i=0;i<MAX;i++)
{
nums[i] = i; //Place numbers from 1 to 100 in the array
}
for (i=0;i<MAX;i++) //Loops through each number in the array
{
for (j=2;j<=9;j++)
/* This loop iterates from 2 to 9 and checks if
the current number is divisible by it. If it is,
it replaces it with 0.*/
{
if (nums[i] == 1 || nums[i] == 4 || nums[i] == 6 || nums[i] == 8 || nums[i] == 9 || nums[i] == 10 )
/*Excludes non-primes less than 11*/
{
nums[i] = 0;
}
if ((nums[i]%j)==0 && nums[i] > 11)
{
nums[i] = 0;
}
}
}
for (i=0;i<MAX;i++)
{
printf("%d ", nums[i]);
}
return 0;
}
提前感谢您的帮助!
【问题讨论】:
-
你的程序是 O(n^1.5),而不是 O(n^2)。查找需要 O(n loglogn) 的 Eratosthenes 筛,或者更快的更复杂的 Atkin 筛。
-
注意:评论是off-by-1
//Place numbers from 1 to 100 in the array-->Place numbers from 0 to 99 in the array -
是什么让你相信存在 O(N) 算法?
-
@Prune,根据en.wikipedia.org/wiki/Generating_primes#complexity,有线性时间筛,它们不像 Erastothenes 那样简单。