(Problem 37)Truncatable primes
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.
题目大意:
3797这个数很有趣。它本身是质数,而且如果我们从左边不断地裁去数字,得到的仍然都是质数:3797,797,97,7。而且我们还可以从右向左裁剪:3797,379,37,3,得到的仍然都是质数。
找出全部11个这样从左向右和从右向左都可以裁剪的质数。
注意:2,3,5和7不被认为是可裁剪的质数。
//(Problem 37)Truncatable primes // Completed on Thu, 31 Oct 2013, 13:12 // Language: C // // 版权所有(C)acutus (mail: acutus@126.com) // 博客地址:http://www.cnblogs.com/acutus/ #include<stdio.h> #include<math.h> #include<string.h> #include<ctype.h> #include<stdlib.h> #include<stdbool.h> bool isprim(int n) { int i=2; if(n==1) return false; for(; i*i<=n; i++) { if(n%i==0) return false; } return true; } bool truncatable_prime(int n) { int i,j,t,flag=1; char s[6]; int sum=0; sprintf(s,"%d",n); int len=strlen(s); if(!isprim(s[0]-'0') || !isprim(s[len-1]-'0')) return false; for(i=1; i<len-1; i++) { t=s[i]-'0'; if(t==0 || t==2 || t==4 || t==6 || t==5 || t==8) return false; } for(i=1; i<len-1; i++) { for(j=i; j<len-1; j++) { sum+=s[j]-'0'; sum*=10; } sum+=s[j]-'0'; if(!isprim(sum)) return false; sum=0; } j=len-1; i=0; while(j>i) { for(i=0; i<j; i++) { sum+=s[i]-'0'; sum*=10; } sum+=s[i]-'0'; if(!isprim(sum)) return false; sum=0; i=0; j--; } return true; } int main() { int sum,count; sum=count=0; int i=13; while(1) { if(isprim(i) && truncatable_prime(i)) { count++; sum+=i; //printf("%d\n",i); } i=i+2; if(count==11) break; } printf("%d\n",sum); return 0; }
Answer:
|
748317 |
作者:acutus
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.