R 684个字符
f=function(N){r=rowSums;p=function(x,y)r(!outer(x,y,`%%`));S=sum;x=c(1,1);n=600851475143;a=900:999;b=20;c=1:100;m=2:sqrt(n);M=m[!n%%m];A=a%o%a;d=3;P=2;z=1:1e3;Z=expand.grid(z,z);Y=cbind(Z,sqrt(r(Z^2)));W=gsub("\n","",xpathApply(htmlParse("http://projecteuler.net/problem=8"),"//p",xmlValue)[[2]]);switch(N,S(which(p(1:999,c(3,5))>0)),{while(tail(x,1)<4e6)x=c(x,S(tail(x,2)));S(x[!x%%2])},max(M[p(M,M)<2]),max(A[sapply(strsplit(c(A,""),""),function(x)all(x==rev(x)))],na.rm=T),{while(any(b%%1:20>0))b=b+20;b},S(c)^2-S(c^2),{while(P<=1e4){d=d+2;if(sum(!d%%2:d)<2)P=P+1};d},max(sapply(5:nchar(W),function(i)prod(as.integer(strsplit(substr(W,i-4,i),"")[[1]])))),prod(Y[r(Y)==1000,][1,]))}
缩进:
f=function(N){
r=rowSums
p=function(x,y)r(!outer(x,y,`%%`))
S=sum
x=c(1,1)
n=600851475143
a=900:999
b=20
c=1:100
m=2:sqrt(n)
M=m[!n%%m]
A=a%o%a
d=3
P=2
z=1:1e3
Z=expand.grid(z,z)
Y=cbind(Z,sqrt(r(Z^2)))
W=gsub("\n","",xpathApply(htmlParse("http://projecteuler.net/problem=8"),"//p",xmlValue)[[2]])
switch(N,S(which(p(1:999,c(3,5))>0)),
{while(tail(x,1)<4e6)x=c(x,S(tail(x,2)));S(x[!x%%2])},
max(M[p(M,M)<2]),
max(A[sapply(strsplit(c(A,""),""),function(x)all(x==rev(x)))],na.rm=T),
{while(any(b%%1:20>0))b=b+20;b},
S(c)^2-S(c^2),
{while(P<=1e4){d=d+2;if(sum(!d%%2:d)<2)P=P+1};d},
max(sapply(5:nchar(W),function(i)prod(as.integer(strsplit(substr(W,i-4,i),"")[[1]])))),
prod(Y[r(Y)==1000,][1,]))
}
用法:
> f(1)
[1] 233168
> f(2)
[1] 4613732
> f(3)
[1] 6857
> f(4)
[1] 906609
> f(5)
[1] 232792560
> f(6)
[1] 25164150
> f(7)
[1] 104743
> f(8)
[1] 40824
> f(9)
[1] 31875000
分别:
1:48个字符 sum(which(rowSums(!outer(1:999,c(3,5),`%%`))>0))
2:64个字符 x=c(1,1);while(tail(x,1)<4e6)x=c(x,sum(tail(x,2)));sum(x[!x%%2])
3:73个字符 n=600851475143;m=2:sqrt(n);M=m[!n%%m];max(M[rowSums(!outer(M,M,`%%`))<2])
4:88个字符 a=900:999;b=a%o%a;max(b[sapply(strsplit(c(b,""),""),function(x)all(x==rev(x)))],na.rm=T)
5:34个字符 a=20;while(any(a%%1:20>0))a=a+20;a
6:25个字符 a=1:100;sum(a)^2-sum(a^2)
7:54个字符 d=3;P=2;while(P<=1e4){d=d+2;if(sum(!d%%2:d)<2)P=P+1};d
8:181个字符
第一行从项目欧拉网站上读取数字,第二行实际执行计算。
W=gsub("\n","",xpathApply(htmlParse("http://projecteuler.net/problem=8"),"//p",xmlValue)[[2]])
max(sapply(5:nchar(W),function(i)prod(as.integer(strsplit(substr(W,i-4,i),"")[[1]]))))
9:87个字符 z=1:1e3;Z=expand.grid(z,z);Y=cbind(Z,sqrt(rowSums(Z^2)));prod(Y[rowSums(Y)==1000,][1,])
if(i%3<1||i%5<1)a+=i
更短!:)