在hackerearth中获取TLE
Posted
技术标签:
【中文标题】在hackerearth中获取TLE【英文标题】:Getting TLE in hackerearth 【发布时间】:2018-11-08 09:18:55 【问题描述】:当我在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
我怎样才能分析这段代码并得到 时间复杂度。
【问题讨论】:
什么是 TLE? @u__ 已超过时间限制。这就是需要解决的问题。表面上的任务通常并不像找到一个有效的解决方案那么困难。 通常能够推导出特定算法的时间复杂度对于改进它非常有用。 有很多关于更高效素数算法的 SO 示例。例如,为什么要检查每个偶数除数? 2 是唯一的偶数素数。仅此更改就会将运行时间减半。 请给您的问题起一个更具描述性的标题,以便其他有类似问题的用户可以找到它。 【参考方案1】:您的checkprime
函数需要大量运行时间。它运行N/2
操作。
您正在为所有数字运行此操作,因此您正在运行 N*N/2
操作,这太多了。
我建议您使用更好的方法来生成素数。看看the Sieve of Eratosthenes
【讨论】:
即使检查所有奇数(和 2)直到sqrt(N)
也可能会成功。或者所有6n+1
和6n-1
,如果你想花哨的话。
谢谢大家的好意:)【参考方案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
是一种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;
【讨论】:
以上是关于在hackerearth中获取TLE的主要内容,如果未能解决你的问题,请参考以下文章
代码在我的计算机上运行良好,但在“hackerearth”平台上在线运行时出现 NullPointerException
iOS 从带有 JSON 参数的 AFNetworking HTTP POST 方法获取 JSON 响应
优化:Hackerearth Postman 软件工程师实习生问题
为啥这只是一个角落案例失败?问题链接-https://www.hackerearth.com/problem/algorithm/chandu-and-his-interns/description/