标签:int span prim gif sum tar alt dig detail
题目要求是不超过1s
自己写的代码如下:注意sqrt处的=
1 bool isP(int n) 2 { 3 int dig = 0; 4 int sum = 0; 5 int m = n; 6 while (n) 7 { 8 dig = n % 10; 9 n = n / 10; 10 sum = sum * 10 + dig; 11 } 12 13 if (sum == m) return true; 14 else return false; 15 16 } 17 bool isprimer(int n) 18 { 19 for (int i = 2; i <=sqrt(n); i++) 20 if (n%i == 0) return false; 21 return true; 22 } 23 int main() 24 { 25 26 int l, r; 27 while (cin >> l >> r) 28 { 29 int count = 0; 30 for (int i = l; i <= r; i++) 31 { 32 if (isP(i) && isprimer(i)) count++; 33 } 34 cout << count << endl; 35 } 36 }
只能通过70%,原因是isprimer的效率不够高,这两个函数的先后调用顺序也要注意
http://blog.csdn.net/tigerisland45/article/details/70236364
高效率的素数为:
1 bool isprime(int n) 2 { 3 if(n == 1) 4 return false; 5 6 if(n == 2) 7 return true; 8 9 if(n % 2 == 0) 10 return false; 11 12 int end = sqrt(n); 13 for(long i=3; i<=end; i+=2) 14 if(n % i == 0) 15 return false; 16 17 return true; 18 }
标签:int span prim gif sum tar alt dig detail
原文地址:http://www.cnblogs.com/hchacha/p/7669537.html