File: primes.4th

package info (click to toggle)
kforth 20010227-2
  • links: PTS
  • area: main
  • in suites: woody
  • size: 508 kB
  • ctags: 652
  • sloc: asm: 2,026; cpp: 1,795; ansic: 575; makefile: 64
file content (59 lines) | stat: -rw-r--r-- 1,131 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
\ primes.4th
\
\ Example code for kForth
\ Copyright (c) 1998 Creative Consulting for Research and Education
\

\ Test for a prime number. Return the largest divisor (< n ) 
\ and a flag indicating whether the number is prime or not.

: ?prime ( n -- m flag | is n a prime number? )
\ if flag is false (0), m is the largest divisor of n
    abs
    dup 3 >		\ is n > 3 ?
    if
      dup 2 /mod
      swap 0= 
      if		\ is n divisible by 2 ?
        nip false
      else
        1-		\ check for divisibility starting	  
        begin		\ with n/2 - 1 and counting down
          2dup mod
          over 1 >
          and
        while
          1-
        repeat
        nip
        dup 1 <=
      then 
    else
      drop 1 true 
    then
;

: test_prime ( n -- | test for prime number and display result )
    ?prime
    if
      ." is a prime number" drop
    else
      ." is NOT prime. Its largest divisor is " .
    then
    cr
;

: list_primes ( n -- | list all the prime numbers from 1 to n )
    abs
    dup 0>
    if 
      1+ 1 do
        i ?prime 
	if i . cr then 
	drop
      loop
    else
      drop
    then
;