让你的列表大小为 x,数字为 n。然后期望 x* sqrt(n) 的时间复杂度
1-找到所有素数直到 n 的 sqrt
2-对于除n但列表中没有元素的每个素数,添加到结果集中
3- 返回结果集
public static List<Integer> uniqueFactors(int n, int[] list){
//find possible prime factors of n: O(sqrt(n))
int factors = (int)Math.sqrt(n);
boolean [] P = new boolean[factors+1];
Arrays.fill(P, true);
P[0]=P[1]= false;//0 and 1 are not primes
int limit =(int) Math.sqrt(factors)+1;//prime search limit
for(int i=2; i <= limit; i++ )
if(P[i]) {
int y;
for(int x=2; (y=x*i)<=factors; x++)
if(P[y])
P[y]=false;
}
//retrieve/identify all prime factors of n that are not prime factors of elements in list
//O is sqrt(n) * list
List<Integer> result = new ArrayList<Integer>();
for(int i=2; i<=factors; i++)
if(P[i] && n%i==0) {//if i is prime and a factor of n
boolean shared = false;
for(int el: list)
if(el%i==0) {
shared=true;
break;
}
if(!shared)
result.add(i);
}//if
return result;
}//uniqueFactors
测试
public static void main(String[] args) {
int n=2*3*5*7*11*13*17*19;
int list[]= {8,9,25,98,121,38};
System.out.println(uniqueFactors(n,list));
}
print out: [13, 17]
我运行的解决方案的所有其他变体仍然以 Big-O 结尾: sqrt(n) * list_size