Problem 37 Truncatable primes (暴力)

素颜马尾好姑娘i 2022-07-15 02:26 194阅读 0赞

Truncatable primes

Problem 37

The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.

Find the sum of the only eleven primes that are both truncatable from left to right and right to left.

NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.




















Answer:
748317
Completed on Sat, 29 Oct 2016, 15:27

代码:

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int is_prime(int n)
  4. {
  5. if(n <= 1) return 0;
  6. if(n == 2 || n == 3) return 1;
  7. else if (n % 2 == 0) return 0;
  8. else
  9. {
  10. for(int i=3;i<(int)sqrt((float)n)+1;i++)
  11. {
  12. if(n % i == 0) return 0;
  13. }
  14. }
  15. return 1;
  16. }
  17. int truncatable(int n) //左移右移后是否是素数
  18. {
  19. if (n<=0) return 0;
  20. //n的长度
  21. int len = 0;
  22. int cpy = n;
  23. while (cpy !=0)
  24. {
  25. len ++;
  26. cpy /= 10;
  27. }
  28. //右移
  29. cpy = n;
  30. while (cpy !=0)
  31. {
  32. if(!is_prime(cpy))
  33. {
  34. return 0;
  35. }
  36. cpy /= 10;
  37. }
  38. //左移
  39. cpy = n;
  40. while(len>1)
  41. {
  42. int x = cpy % (int)pow((float)10,len-1); //低位取模
  43. if (!is_prime(x))
  44. {
  45. return 0;
  46. }
  47. len--;
  48. }
  49. return 1;
  50. }
  51. int main()
  52. {
  53. int cnt = 0,sum=0,i=8;
  54. while(cnt< 11)
  55. {
  56. if (truncatable(i))
  57. {
  58. sum += i;
  59. cnt ++;
  60. cout<<i<<endl;
  61. }
  62. i++;
  63. }
  64. cout<<endl;
  65. cout<<"sum="<<sum<<endl;
  66. return 0;
  67. }

发表评论

表情:
评论列表 (有 0 条评论,194人围观)

还没有评论,来说两句吧...

相关阅读