File: primes.fs

package info (click to toggle)
fcode-utils 1.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 46,768 kB
  • sloc: ansic: 9,717; csh: 241; makefile: 129; sh: 17
file content (68 lines) | stat: -rw-r--r-- 1,327 bytes parent folder | download | duplicates (5)
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
60
61
62
63
64
65
66
67
68
\ primes.4th

fcode-version2

\ Example code for kForth
\ Copyright (c) 1998 Creative Consulting for Research and Education
\
\ This program is free software; you may redistribute it under the terms of
\ the GNU General Public License.  This program has absolutely no warranty.


\ 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
;
 
10000 list_primes

fcode-end