在 hackerearth 中获取 TLE

Getting TLE in hackerearth

当我在 hackerearth 提交此代码时,我遇到了 TLE。

任何建议我如何优化它 代码。

#include <stdio.h>
#include <stdlib.h>

int checkPrime(int);

int main() {
int a, b,
    reminder,sum=0,n;

    scanf("%d %d",&a,&b);

    while(a <= b) {
        n = a;
        sum = 0;
        reminder = 0;

        while (n > 0) {
        reminder = n % 10;
        sum += reminder;
        n = n / 10;
        }

        if(sum > 1 && checkPrime(sum) == 1 && checkPrime(a) == 1) {
            printf("%d ",a);  
        }

        ++a;
    }

return 0;
}

int checkPrime(int p) {

int i,flag=1;

for(i=2; i <= p / 2; i++){
    if(p%i == 0)  {
        flag = 0;
        break;  
    }
}

return flag;

}

Here is the problem i coded for

我如何分析这段代码并得到 时间复杂度。

您的 checkprime 函数需要大量运行时间。它运行 N/2 次操作。

你是运行所有数字,所以你是运行N*N/2操作,这太多了。

我建议您使用更好的生成素数的方法。看看the Sieve of Eratosthenes

有一些像这样的原始方法,例如循环奇数和一些更多的优化

int isPrime ( int n )
{
    if (n <= 1) return 0; // zero and one are not prime
    unsigned int i;
    for (i=2; i*i<=n; i++) {
        if (n % i == 0) return 0;
    }
    return 1;
}

Seive 有点 over-kill,在你的情况下(如果你没有考虑你的内存需求)因为范围可能非常非常大大 1000000 你可能想使用某种位图来生成 Seive。

这里有一个关于如何生成和使用 Seive 的非常松散的想法。

char *seive;

void generate_seive( int n )
{
        seive = calloc( 1, n );
        if( !seive )
        {
                printf("E...");
                exit(0);
        }

        // Generate Seive 
        for( int i = 2; i < n ; i ++)
        {
                if( seive[i] == 1 )
                        continue;
                // Essentially mark all primes as 0 and
                // non-primes as 1's
                seive[i] = 0;
                for( int j = i + i ; j < n ; j += i )
                        seive[j] = 1;
        }
}

int main()
{
        generate_seive(100);

        // Iterating through the generated Seive 
        // should do
        for( int i = 2; i < 100 ; i ++ )
                if( seive[i] == 0 )
                        printf("%d\n", i);
        return 0;
}