# an attempt at code golf

This article is originally published at https://xianblog.wordpress.com

**H**aving discovered codegolf on Stack Exchange a few weeks ago, I spotted a few interesting puzzles since then but only got the opportunity at a try over a quiet and rainy weekend (and Robin being on vacation)! The challenge was to write an R code for deciding whether or not a given integer n is congruent or not, when congruent means that it is the surface of a rectangle triangle with all three sides rational. The question included a pointer to the Birch and Swinnerton-Dyer conjecture as a mean to check congruence although the real solution was provided by Tunnell’s Theorem, which states that n is congruent if and only if the number of integer solutions to 2x²+y²+8z²=n is twice as much as the number of integer solutions to 2x²+y²+32z²=n if n is odd and the number of integer solutions to 8x²+y²+16z²=n is twice as much as the number of integer solutions to 8x²+y²+64z²=n if n is even. Although this is only true for squared-free integers. (I actually spent more time on figuring out the exact wording of the theorem than on optimising the R code!)

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.

Thanks for visiting r-craft.org

This article is originally published at https://xianblog.wordpress.com

Please visit source website for post related comments.