Find the sum of all eleven primes that are both truncatable from left to right and right to left.
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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | library(gmp) n <- 11:1000000 idx <- as.logical(sapply(n, isprime)) p <- n[idx] truncate.right <- function(n){ flag <- 0 tr.n <- floor(n/10) if (isprime(tr.n) == 2){ if (tr.n < 10){ flag <- 1 }else { flag <- truncate.right(tr.n) } } return (flag) } flag.list <- sapply(p, truncate.right) p1 <- p[as.logical(flag.list)] flag.list <- c() for (i in p1) { flag <- 0 i.length <- length(unlist(strsplit(as.character(i),''))) tr.l <- sapply(1:i.length,function(x) i %% 10^x) is.p <- sapply(tr.l, isprime) if (length(which(is.p==2)) == i.length) flag <- 1 flag.list <- c(flag.list,flag) } p2 <- p1[as.logical(flag.list)] sum(p2) |
在我的机子上,15秒就算完了... yeah.........
Answer: 748317

昨天去玩了一下,刚做了前2题,哈哈
Reply
ygc
Reply:
October 4th, 2008 at 12:39 pm
前几题是送分的.....
Reply
azalea
Reply:
October 5th, 2008 at 10:21 am
是啊 不用想啊。。
Reply
问个问题,你这里代码中很多关键字的的超链接是怎么回事?糟糕的是,我复制了一段小例子,怎么我博客上显示的也是带超链接的阿,怎么才能去掉?
Reply
ygc
Reply:
April 19th, 2011 at 10:04 am
复制请写明原文地址。
Reply