Fractran: Difference between revisions

→‎{{header|Scheme}}: corrected, but please improve because I'm a complete n00b!
m (→‎showing all terms: simplified the program.)
(→‎{{header|Scheme}}: corrected, but please improve because I'm a complete n00b!)
Line 3,661:
 
=={{header|Scheme}}==
{{incorrect|Scheme|primes 29,31,47,59 missing, 20th prime is 71}}
 
Scheme naturally handles fractions, translating to integers as required.
The first part of the code translates from a string representation, as required, but equally the user could type the list of fractions in directly as a list.
 
Similar to Python implementation of generating primes, the power of 2 is detected by first converting the number to binary representation, and check if it has only 1 "1" bit.
<lang scheme>
<lang scheme>(import (scheme base)
(scheme inexact)
(scheme read)
Line 3,707 ⟶ 3,705:
;; Extra Credit: derive first 20 prime numbers
(define (generate-primes target-number initial-n)
(define (is-power-of-two? n) ; a binary with only 1 "1" bit is a power of 2
(andcond (>(<= n 2) ; exclude 2 and 1
(integer? (log n 2)))#f)
(else
(define (extract-prime n)
(let loop ((i 0) (acc 0) (binary-str (number->string n 2)))
(exact (log n 2)))
(cond ((= i (string-length binary-str))
#t)
((and (eq? (string-ref binary-str i) #\1) (= 1 acc))
#f)
((eq? (string-ref binary-str i) #\1)
(loop (+ 1 i) (+ 1 acc) binary-str))
(else
(loop (+ 1 i) acc binary-str)))))))
(define (extract-prime n) ; just gets the number of zeroes in binary
(let ((binary-str (number->string n 2)))
(- (string-length binary-str) 1)))
;
(let loop ((count 0)
Line 3,728 ⟶ 3,737:
 
(display "Primes:\n")
(generate-primes 20 2) ; create first 20 primes</lang>
 
</lang>
 
{{out}}
<pre>Task: 2 15 825 725 1925 2275 425 390 330 290 770 910 170 156 132 116 308 364 68 4
<pre>
Task: 2 15 825 725 1925 2275 425 390 330 290 770 910 170 156 132 116 308 364 68 4
Primes:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89
</pre>
 
535

edits