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.
1 #include<stdio.h> 2 #include<math.h> 3 #include<string.h> 4 #include<ctype.h> 5 #include<stdlib.h> 6 #include<stdbool.h> 7 8 bool isprim(int n) 9 { 10 int i=2; 11 if(n==1) return false; 12 for(; i*i<=n; i++) 13 { 14 if(n%i==0) return false; 15 } 16 return true; 17 } 18 19 bool truncatable_prime(int n) 20 { 21 int i,j,t,flag=1; 22 char s[6]; 23 int sum=0; 24 sprintf(s,"%d",n); 25 int len=strlen(s); 26 27 if(!isprim(s[0]-'0') || !isprim(s[len-1]-'0')) return false; 28 29 for(i=1; i<len-1; i++) 30 { 31 t=s[i]-'0'; 32 if(t==0 || t==2 || t==4 || t==6 || t==5 || t==8) return false; 33 } 34 35 for(i=1; i<len-1; i++) 36 { 37 for(j=i; j<len-1; j++) 38 { 39 sum+=s[j]-'0'; 40 sum*=10; 41 } 42 sum+=s[j]-'0'; 43 if(!isprim(sum)) return false; 44 sum=0; 45 } 46 j=len-1; 47 i=0; 48 while(j>i) 49 { 50 for(i=0; i<j; i++) 51 { 52 sum+=s[i]-'0'; 53 sum*=10; 54 } 55 sum+=s[i]-'0'; 56 if(!isprim(sum)) return false; 57 sum=0; 58 i=0; 59 j--; 60 } 61 return true; 62 } 63 64 int main() 65 { 66 int sum,count; 67 sum=count=0; 68 int i=13; 69 while(1) 70 { 71 if(isprim(i) && truncatable_prime(i)) 72 { 73 count++; 74 sum+=i; 75 //printf("%d\n",i); 76 } 77 i=i+2; 78 if(count==11) break; 79 } 80 printf("%d\n",sum); 81 return 0; 82 }
Answer:
| 748317 |