A Dozen Lines Of Code
January 24, 2012
Long-time readers of this blog will not be surprised that I based my program on prime numbers, because I think they’re really cool. I wrote three basic functions related to prime numbers. The first function uses the sieve of Eratosthenes to make a list of prime numbers less than n:
; primes n -- list of primes not greater than n in ascending order
(define (primes n) ; assumes n is an integer greater than one
(let* ((len (quotient (- n 1) 2)) (bits (make-vector len #t)))
(let loop ((i 0) (p 3) (ps (list 2))) ; sieve of eratosthenes
(cond ((< n (* p p))
(do ((i i (+ i 1)) (p p (+ p 2))
(ps ps (if (vector-ref bits i) (cons p ps) ps)))
((= i len) (reverse ps))))
((vector-ref bits i)
(do ((j (+ (* 2 i i) (* 6 i) 3) (+ j p)))
((<= len j) (loop (+ i 1) (+ p 2) (cons p ps)))
(vector-set! bits j #f)))
(else (loop (+ i 1) (+ p 2) ps))))))
The second function uses the Miller-Rabin algorithm to determine if a number is probably prime; it uses the first 25 primes as witnesses in a strong-pseudoprime test. The first line abuses the concept of a line, but otherwise the function is properly written:
; prime? n -- #f if provably composite, else #t if probably prime
(define prime? (let ((ps (primes 100))) (lambda (n) ; integer n
(define (spsp? n a) ; #f if n is provably composite, else #t
(do ((d (- n 1) (/ d 2)) (s 0 (+ s 1)))
((odd? d)
(if (= (expm a d n) 1) #t
(do ((r 0 (+ r 1)))
((or (= (expm a (* d (expt 2 r)) n) (- n 1)) (= r s))
(< r s)))))))
(if (member n ps) #t
(do ((ps ps (cdr ps)))
((or (null? ps) (not (spsp? n (car ps)))) (null? ps)))))))
The third function uses Pollard’s rho algorithm to find the factors of an integer; it takes any integer, including negative numbers, which may be stretching the mathematical definition of factoring, but such factorizations are occasionally useful. Notice that there is no limit, so the function will continue to work until it completes the requested factorization, which will be a while in the case where the factors are large. This was the hardest function to contort into twelve lines, and required several rewrites as well as several instances of abuse of the concept of a line:
; factors n -- list of prime factors of n in ascending order
(define (factors n) ; assumes n is an integer, may be negative
(if (<= -1 n 1) (list n) (if (< n 0) (cons -1 (factors (- n)))
(let fact ((n n) (c 1) (fs (list))) ; pollard rho method
(define (f x) (modulo (+ (* x x) c) n))
(if (even? n) (fact (/ n 2) c (cons 2 fs)) (if (= n 1) fs
(if (prime? n) (sort < (cons n fs))
(let loop ((t 2) (h 2) (d 1))
(if (= d 1) (let ((t (f t)) (h (f (f h))))
(loop t h (gcd (- t h) n)))
(if (= d n) (fact n (+ c 1) fs)
(if (prime? d) (fact (/ n d) (+ c 1) (cons d fs))
(fact n (+ c 1) fs))))))))))))
Those aren’t the best functions of their kind, but they’re not bad, either, suitable for a modest library on the subject; taken together, they will solve all the prime-number problems at Project Euler.
We used expm
from the Standard Prelude. You can run the program at http://programmingpraxis.codepad.org/soelfszm.
In ruby, less than a dozen lines you can write a program to display the frequency all the words in a file (“word” defined loosely here as C/C++ style identifier, except it also accepts leading digits as “words” so it should do a reasonable job for text (i.e. not programming language) documents)
Analyzing itself:
Here’s my solution:
;; A simple Boss Key app. My contribution to the dozen-line program contest.
NeedToHide = .*(Mozilla|Explorer|Chrome).*
WantToShow = .*emacs.*
#b::
SetTitleMatchMode, RegEx
WinGet, id, list, %NeedToHide%
Loop, %id% {
this_id := id%A_Index%
WinHide, ahk_id %this_id%
}
WinActivate, %WantToShow%
Return,
And some explanation behind it: http://benjisimon.blogspot.com/2012/01/my-dozen-lines-of-code.html
[…] today’s Programming Praxis exercise, our goal is to make any program we want, as long as it’s cool […]
My Haskell program, which is an 11-line implementation of Conway’s Game of Life (see http://bonsaicode.wordpress.com/2012/01/24/programming-praxis-a-dozen-lines-of-code/ for a version with comments):
Note that I am not counting the import statements as lines of code.
For the above, substitute od.path for os.path.
To use pinc.py as a quine, try: [tt]echo “(> pinc.py >)” | python pinc.py[/tt]
def add(x,y): #assumes both numbers are postive.
while y > 0:
x,y = x^y, (x&y)<0:
if y&1 == 1:
total = add(total,x)
x = x<>1
return x
{/sourcecode]
hmm the source code optino didnt work very well. heres the pastebin option
code
This computes a Brent-Salamin approximation to pi with k digits base b.
Edited from the Gambit examples.
> (pi-brent-salamin 10 100)
31415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170374
I’ve modified one of my old snippets… (see my website for the original)
Okay, I admit that the lines are a bit overfull… but the result quite worths it,
see an image here.
A python program that generates high frequencies can be used as a dog whistle and also to annoy your friends.
from winsound import *;import random
while True:Beep(random.randint(300,1000),random.randint(500,1000))
Perl iterative permutation algorithm (Fischer-Krause) to permute the characters of a string.
11 lines (although slightly abused with the 1-line while loops), max width of 67 characters:
Driver/demo program:
Output:
The ‘Divisors’ Problem (https://programmingpraxis.com/2012/02/14/divisors/) under 12 lines :P
How can we not have here a linearithmic (more or less) primes generating code in 8 lines of Haskell: :)
Test it at http://codepad.org/Z62VCphw.
Forgot to mention that the code itself is a _genuine one-liner_; all the rest are general auxiliary utilities. :)
For instance, the intersection of two ordered increasing lists – a function not used in `primes` – is