C中素数算法的问题
按照 @neal aise 此处获取素因数的答案: 我做了:
/*neal aise's code*/
printPrimeFactors(int num) {
int i;
for (i = 2; i < sqrt(num); i=next_prime(i)) {
if (num %i){
printf("%d", i);
}
}
}
/*my code*/
int next_prime(int p){
int prime_found = 0;
while (!prime_found){
if (p <= 1)/* if low number comes in, then */
p = 2; /* next prime is always 2 (first prime) */
else
if ((p % 2) == 0) /* no even primes */
p++; /* make the number odd before test */
else
p += 2; /* get next odd numero to test */
prime_found = is_prime(p); /*check if number is prime*/
}
return (p);
}
int is_prime(int p){
int curr_num = 2; /* start divisor at 2 */
float stop_num = sqrt((float) p); /* no divisor > sqrt of number needed */
while(curr_num <= stop_num){
if ((p % curr_num) == 0) /* not prime if evenly divisible */
return (0);
else
curr_num++; /* increment divisor */
}
return(1); /* not evenly divisible, return prime */
}
如何修改函数中的代码
printPrimeFactors()
那么它可以按预期工作吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果你想要“素数生成器”,接口对我来说就可以。但是你的代码限制了素数的数量。
无意义的接口没有价值。可以写得更简单。
If you want "prime number generator", interfaces is ok to me. But your code limit the number of prime numbers.
meaningless interfaces is not valuable. it can write more simply.
这里存在一些逻辑错误:
此外,通过停在 处,您只能打印出大约一半的素因数。要么将 for 循环的退出条件更改为
i <= num
:或者采用更有效的替代方法。请注意,这些因素不会按顺序排列:
There are a couple of logic errors:
Also, you will only print out roughly half of the prime factors by stopping at
<sqrt(num)
. Either change the exit condition of the for loop to bei <= num
:Or the alternative, more efficient method. Note the factors will not be in order:
您可以像 if(n*n < n_limit) 那样执行 x = sqrt(n_limit) 和 if(n < x) 操作。不需要昂贵的 sqrt()、float 或cast。
Instead of x = sqrt(n_limit) and if(n < x), you can do it like if(n*n < n_limit). No need for expensive sqrt(), floats or casts.