c - 寻找最接近的质数

标签 c primes compile-time

这不是一个容易问的问题。 我正在编写一个代码,它会询问“n”。然后要求n个数字,最后打印与其中一个最接近的素数有多远。 问题是编译时间应该少于 4 秒,而我无法在 5 秒内得到它。

 #include <stdio.h>
int f (int n){
    int i;
    int a;
    int b;
    int dif=0;
    for ( i = 2 ; i<n ; i++) 
        if (n%i == 0)
            return 0;
    if (n == 0 || n == 1)
        return 0; 
    return 1;

}
int main (){
    int dif=0;
    int difall=10000;
    int a;
    int b;
    int input;
    long long input2;
    scanf("%d",&input);
    int i;
    for (i == 1;i<input;i++){
        scanf("%d",&input2);
        dif=0;
        while (1==1){
        a=input2+dif;
        b=input2-dif;
        if (f(a) == 1 && a>=0){
            if (dif<difall)
                difall=dif;
            break;}
        if (f(b) == 1 && b>=0){
            if (dif<difall)
                difall=dif;
            break;}
        dif++;

    }
    }
    printf("%d",difall);
}

最佳答案

The problem is the compile1 time should be less than 4 secs and I can't get it under 5 s.

测试素数有许多潜在的优化。

OP 当前迭代 [2...n)

// slow
for ( i = 2 ; i<n ; i++) 
        if (n%i == 0)
            return 0;

仅需要 [2...sqrt(n)]。

// faster
for ( i = 2; i <= n/i; i++) {
  if (n%i == 0) {
    return 0;
  }
}

可能存在其他问题,但上述问题会加快代码速度。

<小时/>

1 当然,运行时间是这里的问题。

关于c - 寻找最接近的质数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53320995/

相关文章:

c - 如果其他库中存在相同的函数,如何要求库使用其内部函数

c - 函数的隐式声明 'scan_s' [-Wimplicit-function-declaration]

c - 如何链接同名的 .c 和 .h 文件?

python - python中的素数生成代码

java - Java中将素数从一个数组复制到另一个数组的方法

python - 我是否检查过该列表的每个连续子集?

c++ - 编译时检查和运行时检查 'at the same time'

c++ - 有什么方法可以确定上下文是否允许使用 "this"?

c++ - 如何为编译时已知的参数的多个值编译函数

使用链表的循环队列