Project Euler: Problem 9

Challenge:

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,

a2 + b2 = c2

For example, 32 + 42 = 9 + 16 = 25 = 52.

There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.

Programming Language:

LISP

Solution:

(defun gen-pytha-triplets ()
  (loop named loop-1 for a from 1 to 1000
     do (loop for b from 1 to 1000
	   do (loop for c from 1 to 1000
		 do (if (and (and (< a b c) (= (+ (* a a) (* b b)) (* c c))) (= (+ a b c) 1000))
			(return-from loop-1 (* a b c)))))))

Overview:

Coming soon…


Programming Language:

x86 Assembly

Solution:

; Takes input (n) and prints all triples (a, b, c) such that a^2 + b^2 = c^2 less than n.

format PE console
entry start

include 'win32a.inc'

; ============================================

section '.text' code readable executable

start:				; the program begins here:
	call	read_hex
	mov	ebx, eax
	
loop_1:
	dec	ebx
	mov	ecx, ebx
	cmp	ebx, 0		; check if we've reached end of outermost loop
				; or if input was zero (0).
	jnz	loop_2		; if not zero, start first inner loop
	jmp	exit		; if so, exit

loop_2:
	dec	ecx
	mov	edi, ecx
	cmp	ecx, 0
	jnz	loop_3
	jmp	loop_1

loop_3:
	dec	edi
	cmp	edi, 0		; check if we've reached end of inner loop
	jnz	square_nums	; if not, print number and decrease by 1
	jmp	loop_2

square_nums:
	mov	esi, 0		; initialize esi (our a^2 + b^2) 
				; part of equation to zero.
	mov	eax, edi	; square least num (loop 3 num), or a.
	mul	edi
	add	esi, eax	; add result (a^2) to esi.
	mov	eax, ecx	; square second least num (loop 2 num), or b.
	mul	ecx
	add	esi, eax	; add result (b^2) to esi.
				; esi now contains (a^2 + b^2).	

	mov	eax, ebx	; square largest num (loop 1 num), or c.
	mul	ebx
	
	cmp	esi, eax	; check is (a^2 + b^2), or esi, equals (c^2) or eax.
	jnz	loop_3		; if not, continue to next group of numbers.
				; otherwise, print numbers.

print_num:
	mov	eax, ebx
	call	print_eax
	mov	eax, ecx
	call	print_eax
	mov	eax, edi
	call	print_eax
	jmp	loop_3		; and continue to test next set of numbers.

exit:				; exit the process:
	
	push	0		
	call	[ExitProcess]

include 'training.inc'

Overview:

Coming soon…