最近心血来潮学了下Racket语言,与命令式的语言不同,它基本的语法规则很简洁,但刚开始写起来也不是那么容易。因此打算用这个语言来刷一下Project Euler,来熟悉一下这个语言。

1. Multiples of 3 and 5

#lang racket
(define answer
  (for/sum ([i (in-range 1000)])
    (if (or (zero? (modulo i 3))
           (zero? (modulo i 5)))
       i 0)))

2. Even Fibonacci numbers

#lang racket
(define (aux lst sum)
  (let ([cur (+ (car lst) (car (cdr lst)))])
       (if (> cur 4000000) sum
           (aux (cons cur lst)
                (if (even? cur) (+ sum cur) sum)))))
(define answer
  (aux '(1 1) 0))

3. Largest prime factor

#lang racket
(require math/number-theory)
(define answer
  (car (last (factorize 600851475143))))

4. Largest palindrome product

#lang racket
(define answer
  (apply max
         (filter positive?
                 (for*/list ([i (in-range 100 1000)]
                             [j (in-range 100 1000)])
                   (let* ([str (number->string (* i j))]
                          [lst (sequence->list str)])
                     (if (equal? lst (reverse lst)) (* i j) -1))))))

5. Smallest multiple

#lang racket
(define answer
  (apply lcm (for/list ([i (in-range 1 21)]) i)))