Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
My original solution
p=function(n){
for (i in(n:2)^2)if(n%%i<1)n=n/i
if(n%%2){d=8;f=2;g=16}else{d=2;f=1;g=8}
A=0;b=(-n:n)^2
for(x in d*b)for(y in x+f*b)for(z in g*b)
A=A+(y+z==n)-2*(y+4*z==n)
A==0}
was quite naïve, as shown by the subsequent improvements by senior players, like the final (?) version of Guiseppe:
function(n){b=(-n:n)^2
for(i in b[b>0])n=n/i^(!n%%i)
P=2^(n%%2)
o=outer
!sum(!o(y<-o(8/P*b,2*b,"+")/P-n,z<-16/P*b,"+"),-2*!o(y,4*z,"+"))}
exhibiting a load of code golf tricks, from using an anonymous function to renaming functions with a single letter, to switching from integers to booleans and back with the exclamation mark.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
