Project Euler: Problem 7

Challenge:

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10,001st prime number?

Programming Language:

LISP

Solution:

(defun isprime-p(n)
  (defparameter isprime NIL)
  (if (and (oddp n) (> n 2))
      (loop for x from 2 below n
	 do (if (eql 0 (mod n x))
		(progn (setq isprime NIL)
		       (return NIL))
		(setq isprime T))))
  (if (eq n 2)
      (setq isprime T))
  (print isprime))

(defun nth-prime(num)
  (defparameter primes NIL)
  (defparameter p 2)
  (loop while (< (list-length primes) num)
     do (if (eql T (isprime-p p))
	(push p primes))
    (setq p (+ 1 p)))
  (print (car primes)))

Overview:

Coming soon…


Programming Language:

x86 Assembly

Solution:

; receives input (n), prints all primes greater than 1 up to 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	; setup counter in ebx

prime_loop:

	cmp	ebx, 1		; check that counter is
	jbe	exit		; below or equal to 1. if so, exit.
				; otherwise, continue.
	mov	eax, ebx	; move counter's value into eax 
				; (input of 'start_check_prime' loop.

start_check_prime:		

	mov	esi, eax	; store input in esi for later.
	cmp	eax, 2		; if input is 2 (special case prime)
	je	prime		; num is prime. jump to 'prime' label.
	cmp	eax, 3		; if input is 3
	je	prime		; also jump to 'prime' label.

	mov	edx, 0		; initialize edx to 0 for div with 32-bit integers [EDX:EAX].
	mov	ecx, 2		; setup divsor (2)
	div	ecx		; check if input is even and 
				; get half its value for prime check.
	cmp	edx, 0		; if edx is 0, remainder of 'div 2' = 0
	je	n_prime		; input is even.
				; Otherwise input is odd. Check for prime.
	mov	ecx, eax	; setup ecx (counter) with half of input
				; and check divisbility by nums up to ecx.

check_prime:			; check for prime loop

	mov	eax, esi	; restore eax with original input for check_prime.
	mov	edx, 0		; initialize edx to 0 for div with 32-bit integers [EDX:EAX].
	div	ecx		; divide by current ecx (counter) value
	cmp	edx, 0		; if input num is evenly divisible by ecx (counter)
	je	n_prime		; then not prime.
	dec	ecx		; decrease counter by 1
	cmp	ecx, 1		; but make sure counter is above 1 (because all nums evenly
	ja	check_prime	; divisible by 1). if counter is above 1, check next ecx num.
				; once all ecx nums are checked, and no jumps have been made
				; from 'check_prime' loop, then number is prime.
				; continue to following line.


prime:				; number is prime.

	mov	eax, esi		
	call	print_eax
	dec	ebx
	jmp	prime_loop

n_prime:			; number is not prime.

	dec	ebx
	jmp	prime_loop


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

include 'training.inc'

Overview:

Coming soon…