Project Euler

Project Euler Problem 66

steloflute 2013. 10. 27. 22:46

http://projecteuler.net/problem=66


Diophantine equation

Problem 66

Consider quadratic Diophantine equations of the form:

x2 – Dy2 = 1

For example, when D=13, the minimal solution in x is 6492 – 13×1802 = 1.

It can be assumed that there are no solutions in positive integers when D is square.

By finding minimal solutions in x for D = {2, 3, 5, 6, 7}, we obtain the following:

32 – 2×22 = 1
22 – 3×12 = 1
92 – 5×42 = 1
52 – 6×22 = 1
82 – 7×32 = 1

Hence, by considering minimal solutions in x for D ≤ 7, the largest x is obtained when D=5.

Find the value of D ≤ 1000 in minimal solutions of x for which the largest value of x is obtained.


Answer:
661



Racket


#lang racket
; x^2 – Dy^2 = 1
(define result 0)
(define pmax 0)

(for ([D (in-range 2 1001)]) 
  (define limit (exact-floor (sqrt D)))
  (unless (= (sqr limit) D)   
    (let* ([m 0] [d 1] [a limit] [numm1 1] [num a] [denm1 0] [den 1])
      (let loop ()
        (unless (= 1 (- (sqr num) (* D den den)))
          (set! m (- (* d a) m))
          (set! d (exact-floor (/ (- D (sqr m)) d)))
          (set! a (exact-floor (/ (+ limit m) d)))
          (define numm2 numm1)
          (set! numm1 num)
          (define denm2 denm1)
          (set! denm1 den)
          (set! num (+ (* a numm1) numm2))
          (set! den (+ (* a denm1) denm2))
          (loop)))
      (displayln (list D num))
      (when (> num pmax)
        (set! pmax num)
        (set! result D)))))
(displayln result)




'Project Euler' 카테고리의 다른 글

Project Euler solutions in Ada  (0) 2016.05.12
Project Euler solutions in Javelin  (0) 2015.10.13
Project Euler Problem 99  (0) 2013.10.27
Project Euler Problem 67  (0) 2013.09.02
Project Euler Solutions in Racket  (0) 2012.10.17