Project Euler

Problem #91

The points P (x_(1), y_(1)) and Q (x_(2), y_(2)) are plotted at integer co-ordinates and are joined to the origin, O(0,0), to form ΔOPQ.


There are exactly fourteen triangles containing a right angle that can be formed when each co-ordinate lies between 0 and 2 inclusive; that is,
0 ≤ x_(1), y_(1), x_(2), y_(2) ≤ 2.


Given that 0 ≤ x_(1), y_(1), x_(2), y_(2) ≤ 50, how many right triangles can be formed?

Erlang: Running time = 23.664s
+%cartesian_product

p91()->
	S=lists:seq(0,50),
	Triangles=lists:filter(fun
				 %
				 % Only using the pairs where the angle of the first point (in polar coordinates)
				 % is greater than the second
				 %

				 ([X,Y,X,Y])->false;
				 ([_,_,0,_])->false; % since the first angle must be greater than the second, X2 cannot be 0
				 ([_,0,_,_])->false; % nor can Y1 be 0
				 ([0,A,B,0])->true;
				 ([A,B,A,0])->true;
				 ([0,A,B,A])->true;
				 ([0,A,B,B]) when A == 2*B->true;
				 ([B,B,A,0]) when A == 2*B->true;
				 ([X1,Y1,X2,Y2]) when Y1/X1 =< Y2/X2->false;
				 ([X1,Y1,X2,Y2])->
				 	L1=X1*X1+Y1*Y1,
					L2=X2*X2+Y2*Y2,
					L3=(X1-X2)*(X1-X2)+(Y1-Y2)*(Y1-Y2),
					[L4,L5,L6]=lists:sort([L1,L2,L3]),
					L4+L5==L6
				 end,cartesian_product([S,S,S,S])),
	io:format("~w~n",[length(Triangles)]).