[英]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;
}
以及如何分析此代碼並獲得時間復雜度。
有一些像這樣的原始方法,例如循環奇數和一些更多的優化
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.