The Way 2 Inner Peace.

欧拉项目第14题.
欧拉项目第28题.

欧拉项目第12题.

Qians posted @ 2012年10月25日 20:48 in scheme with tags projecteuler racket , 856 阅读

https://projecteuler.net/problem=12

计算一个自然数的因子个数,用到了这里

racket...

#lang racket

(define (triangle x)
  (quotient (* x (add1 x)) 2))

(define (prime-factors n)
  (let loop ([n n] [m 2] [factors (list)])
    (cond [(= n 1) factors]
          [(= 0 (modulo n m)) (loop (/ n m) 2 (cons m factors))]
          [else (loop n (add1 m) factors)]))) 

;;cont n in l
(define (count-n l n)
  (cons n (count (lambda (x) (= n x)) l)))

;;count all n in l
(define (count-all l)
  (let loop ([l l] [visited '()] [r '()])
    (cond
      [(null? l) r]
      [(member (car l) visited) (loop (cdr l) visited r)]
      [else (loop (cdr l) 
                  (cons (car l) visited)
                  (cons (count-n l (car l)) r))])))

;;count all divisors of a number
;more in http://bit.ly/WLfeZN
(define (count-factor n)
  (let loop ([l (count-all(prime-factors n))] [r 1])
    (cond
      [(null? l) (cons r n)]
      [else (loop (cdr l) (* r (add1(cdar l))))])))

(define (tri-count-factor n)
  (count-factor (triangle n)))

(time(car(filter (lambda (x) (< 500 (car x))) 
                 (map tri-count-factor (range 10000 20000)))))

 


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter