The limit of Fermat's factorization method

I am trying to implement Fermat's factorization ( Algorithm C in the Art of Computer Programming, Volume 2). Unfortunately, in my edition (ISBN 81-7758-335-2) this algorithm is printed incorrectly. What should be the condition for the factor-inner cycle below? I run the loop until y <= n [accepted as limitation].

(if (< limit y) 0 (factor-inner x (+ y 2) (- r y) limit))

Is there anyway to avoid this condition altogether, since it will double the cycle speed?

(define (factor n) 
  (let ((square-root (inexact->exact (floor (sqrt n))))) 
    (factor-inner (+ (* 2 square-root) 1)
                  1 
                  (- (* square-root square-root) n)
                  n)))

(define (factor-inner x y r limit)
  (if (= r 0)
    (/ (- x y) 2)
    (begin 
      (display x) (display " ") (display y) (display " ") (display r) (newline)
      ;;(sleep-current-thread 1)
      (if (< r 0)
        (factor-inner (+ x 2) y (+  r x) limit)
        (if (< limit y)
          0
          (factor-inner x (+ y 2) (- r y) limit))))))
+3
source share
2 answers

A check is (< limit y)not needed, because in the worst case, the algorithm will eventually find this solution:

x = N + 2

y = N

Then he will return.

+1
source

C, , , C4 , r < 0, x r y.

a, b r 1998 Vol. 2 (ISBN 0-201-89684-2), :

(define (factor n) 
  (let ((x (inexact->exact (floor (sqrt n)))))
    (factor-inner (+ (* x 2) 1)
                  1
                  (- (* x x) n))))

(define (factor-inner a b r)
  (cond ((= r 0) (/ (- a b) 2))
        ((< 0 r) (factor-inner a       (+ b 2) (- r b)))
        (else    (factor-inner (+ a 2) (+ b 2) (- r (- a b))))))

EDIT : , , ,

r <- ((a - b) / 2)*((a + b - 2)/2) - N

0, , , r, a b. b b+2 r , r b, C4 . , .

r > 0, , b, C4. , , r < 0, . , a, a 2 r a, C3. a > b, r a C3 r , C4.

, a > b. a , b, - b , b = a - 2,

N = (a - (a - 2))/2 * ((a + (a - 2) - 2)/2 = 1 * (a - 2)

, N , , , sqrt(N) 1, .

+1

Source: https://habr.com/ru/post/1736955/


All Articles