Ví dụ nghĩ ra thuật toán

Một phần của tài liệu Bài 5 -Algorithms ppsx (Trang 25 - 28)

• G/s ta phải viết thuật toán để tính vị từ:G/s ta phải viết thuật toán để tính vị từ:

IsPrime

IsPrime::NN→→{T,F}{T,F}

– Tính xem số tự nhiên cho trước có phải là số Tính xem số tự nhiên cho trước có phải là số nguyên tố không.

nguyên tố không.

• Trước hết, bắt đầu bằng định nghĩa của logic vị từ Trước hết, bắt đầu bằng định nghĩa của logic vị từ

về hàm định nghĩa số nguyên tố:

về hàm định nghĩa số nguyên tố:

nn: : IsPrimeIsPrime((nn) )  ¬¬∃∃1<1<dd<<nn: : dd||nn

Means d divides n

08/14/14 (c)2001-2003, Michae l P. Frank

26Module #5 - Algorithms Module #5 - Algorithms

IsPrime example, cont.

• Trước hết phủ định của tồn tại biểu diễn qua lượng Trước hết phủ định của tồn tại biểu diễn qua lượng

tử với mọi: tử với mọi: ¬ ¬∃1<∃1<dd<<nn: : dd||n n  ∀1<∀1<dd<<nn: : dd | | nn  ∀2∀2≤ ≤ d d ≤ ≤ nn−1−1: : dd | | nn

• Lượng tử với mọi này có thể dịch trực tiếp thành Lượng tử với mọi này có thể dịch trực tiếp thành

vòng lặp for tương ứng:

vòng lặp for tương ứng:

for

for dd := 2 to := 2 to nn−1 { Try all potential divisors >1 & <−1 { Try all potential divisors >1 & <nn } }

ifif d|nd|n thenthen returnreturn F F { { nn has divisor has divisor dd; not prime }; not prime }

return

return TT { no divisors were found; { no divisors were found; nn must be prime} must be prime}

Means d does not

divide n evenly

08/14/14 (c)2001-2003, Michae l P. Frank

27Module #5 - Algorithms Module #5 - Algorithms

Optimizing IsPrime

• The The IsPrimeIsPrime algorithm can be further optimized: algorithm can be further optimized:

for (adsbygoogle = window.adsbygoogle || []).push({});

for dd := 2 to := 2 to nn1/21/2

ifif dd||n n then return Fthen return F return T

return T

• This works because of this This works because of this theorem: theorem: If If nn has any has any

(integer) divisors, it must have one less than

(integer) divisors, it must have one less than nn1/21/2..

Proof:

Proof: Suppose Suppose nn’s smallest divisor >1 is ’s smallest divisor >1 is aa, and let , and let

b

b ::≡≡ nn//aa. Then . Then nn = = abab, but if , but if aa > > nn1/21/2 then then bb > > nn1/21/2 (since (since aa

is

is nn’s smallest divisor) and so ’s smallest divisor) and so nn = = abab > ( > (nn1/21/2))22 = = nn, an , an absurdity.

absurdity. Further optimizations are possible: - E.g., only try divisors that

are primes less than n1/2.

08/14/14 (c)2001-2003, Michae l P. Frank

28Module #5 - Algorithms Module #5 - Algorithms

Một phần của tài liệu Bài 5 -Algorithms ppsx (Trang 25 - 28)