Your algorithm doesn't seem correct, and there are syntax errors. For example, this condition is plain wrong: (if = #f survives?)
. That's not how you write an if
expression in Scheme - perhaps you meant (if (equal? (survives? position n) #f) ...)
. Start by getting the basics right!
In Wikipedia you'll find a fine explanation of the solution, together with a couple of implementations, which should be easy to write in Scheme. Just for fun, here's my take on an efficient tail-recursive solution, using a named let
:
(define (first-survivor-after position n)
(let loop ([i 1]
[acc 0])
(if (> i n)
(add1 acc)
(loop (add1 i)
(modulo (+ acc position) i)))))
Or equivalently, a non-tail-recursive version using a helper procedure:
(define (first-survivor-after position n)
(define (loop i)
(if (= i 1)
0
(modulo (+ (loop (sub1 i)) position) i)))
(add1 (loop n)))