Monday, August 17, 2009

Euler Project 52

It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.

Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.


My Solution

(defun IsContainSameDigits(n)
(and (string= (sort (format nil "~a" n) 'string<)
(sort (format nil "~a" (* n 2)) 'string<))
(string= (sort (format nil "~a" n) 'string<)
(sort (format nil "~a" (* n 3)) 'string<))
(string= (sort (format nil "~a" n) 'string<)
(sort (format nil "~a" (* n 4)) 'string<))
(string= (sort (format nil "~a" n) 'string<)
(sort (format nil "~a" (* n 5)) 'string<))
(string= (sort (format nil "~a" n) 'string<)
(sort (format nil "~a" (* n 6))))))

(defun Euler52(n)
(loop for i from 10 to n
do(if (IsContainSameDigits i)
(print i))))

Others' Solution

First Solution
(defun digits (num)
(map 'list
#'(lambda (char) (read-from-string (string char)))
(prin1-to-string num)))

(defun sorted-digits (num)
(sort (digits num) #'<))

(defun same-digits (i maxmult)
(let ((d (sorted-digits i)))
(loop for m from 2 to maxmult
if (not (equal (sorted-digits (* m i)) d))
return nil
finally (return t))))

(defun find-same-digits (maxmult)
(loop for i from 100000
if (same-digits i maxmult) return i))

(defun euler52 ()
(find-same-digits 6))

Second Solution
(defun euler52 (&optional (x 1))
(let ((str (transform x 1)))
(if (and (string= str (transform x 2))
(string= str (transform x 3))
(string= str (transform x 4))
(string= str (transform x 5))
(string= str (transform x 6)))
x
(euler52 (+ x 1)))))

(defun transform (x n)
(sort (prin1-to-string (* x n)) #'char>))

Third Solution
(defun euler52 ()
(loop for i from 1
until
(loop for multiplier from 2 to 6
always (same-digits? i (* i multiplier)))
finally (return i)))
(defun same-digits? (a b)
(and (null (set-difference (digits a) (digits b)))
(null (set-difference (digits b) (digits a)))))
(defun digits (n)
(map 'list
#'
(lambda (c) (read-from-string (string c)))
(write-to-string n)))

No comments:

Post a Comment