簡體   English   中英

在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;

}

這是我編碼的問題

以及如何分析此代碼並獲得時間復雜度。

您的checkprime函數需要大量運行時間。 它運行N/2操作。

您正在為所有數字運行此操作,因此您正在運行N*N/2操作,這太多了。

我建議您使用更好的方法來生成素數。 看看埃拉托色尼的篩子

有一些像這樣的原始方法,例如循環奇數和一些更多的優化

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有點過頭了,在你的情況下(如果你沒有考慮你的內存要求)因為范圍可能非常大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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM