From ea7b21a43d121707f3df56148712760fffc004b2 Mon Sep 17 00:00:00 2001 From: d6 Date: Thu, 30 Dec 2021 22:57:22 -0500 Subject: [PATCH] primes32 --- primes32.tal | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 primes32.tal diff --git a/primes32.tal b/primes32.tal new file mode 100644 index 0000000..c53dc49 --- /dev/null +++ b/primes32.tal @@ -0,0 +1,76 @@ +( primes32.tal ) +( ) +( Uses a simple trial-divion method to find primes. ) +( ) +( To determine if x is prime we: ) +( 1. Check if x is 2 (prime) ) +( 2. Check if x is even (not prime) ) +( 3. Starting with i=3, we see if x%i is 0 ) +( a. We increment i by 2 to avoid even i ) +( b. We stop when x < i*i ) +( 4. If we didn't find an i, x is prime. ) +( ) +( This method can be fast for some large composite ) +( numbers but is quite slow for large primes. ) +( ) +( On my machine, 0x7fffffff was determined to be prime ) +( in 0.5 seconds, but 0xfffffffb ran for 7 minutes ) +( without finishing. Both are prime. By contrast ) +( 0xffffffff was found be composite in 0.02 seconds. ) +( ) +( Smaller primes also run fairly quickly: 0x17b5d was ) +( determined to be prime in 0.02 seconds. ) + +%EMIT { #18 DEO } +%DIGIT { #00 SWP ;digits ADD2 LDA EMIT } +%SPACE { #20 EMIT } +%NEWLINE { #0a EMIT } +%EMIT-BYTE { DUP #04 SFT DIGIT #0f AND DIGIT } +%DEBUG { #ff #0e DEO } + +|0100 + ( number to check comes first ) + #7fff #ffff + OVR2 OVR2 ;is-prime32 JSR2 ( test for primality ) + STH ;emit-long JSR2 SPACE STHr EMIT-BYTE NEWLINE ( output ) + #00 DIV #00 ( exit with /0 to make timing easier ) + BRK + +( include 32-bit math library ) +~math32.tal + +( return 01 if x is a prime number, else 00 ) +( works for x >= 2 ) +@is-prime32 ( x** -> bool^ ) + ,&x1 STR2 ,&x0 STR2 ,&x0 LDR2 ,&x1 LDR2 ( store and reload x ) + DUP4 LIT2 &two0 0000 LIT2 &two1 0002 ;ne32 JSR2 ( x is 2? ) + ,¬-two JCN POP4 #01 JMP2r ( 2 is prime ) + ¬-two DUP #01 AND ( x x&1 ) + ,¬-even JCN POP4 #00 JMP2r ( x is even: not prime ) + ¬-even #0000 ,&i0 STR2 #0003 ,&i1 STR2 ( x i<-3 ) + ,&i0 LDR2 ,&i1 LDR2 ( load our candidate, i ) + ,&loop JMP ( jump over register data to loop label ) + [ &i0 0000 &i1 0000 &x0 0000 &x1 0000 ] ( registers ) + &loop ( x i ) + ,&x0 LDR2 ,&x1 LDR2 ,&i0 LDR2 ,&i1 LDR2 ( x i x i ) + DUP4 ;mul32 JSR2 ;lt32 JSR2 ( x i x ) + SWP2 SWP EMIT-BYTE EMIT-BYTE + SWP EMIT-BYTE EMIT-BYTE JMP2r + +( convenience for less branching when printing hex ) +@digits + 30 31 32 33 34 35 36 37 + 38 39 61 62 63 64 65 66