Oleksii Trekhleb | Javascript algorithms (Sieve of eratosthenes)

This is a series of books diving deep into the core mechanisms of the JavaScript language.

 · 1 phút đọc.

This is a series of books diving deep into the core mechanisms of the JavaScript language.

The Sieve of Eratosthenes is an algorithm for finding all prime numbers up to some limit n.

It is attributed to Eratosthenes of Cyrene, an ancient Greek mathematician.

How it works

  1. Create a boolean array of n + 1 positions (to represent the numbers 0 through n)
  2. Set positions 0 and 1 to false, and the rest to true
  3. Start at position p = 2 (the first prime number)
  4. Mark as false all the multiples of p (that is, positions 2 p, 3 p, 4 p… until you reach the end of the array)
  5. Find the first position greater than p that is true in the array. If there is no such position, stop. Otherwise, let p equal this new number (which is the next prime), and repeat from step 4

When the algorithm terminates, the numbers remaining true in the array are all the primes below n.

An improvement of this algorithm is, in step 4, start marking multiples of p from p p, and not from 2 p. The reason why this works is because, at that point, smaller multiples of p will have already been marked false.

Example

Sieve

Complexity

The algorithm has a complexity of O(n log(log n)).

nhavantuonglai

Share:
Quay lại.

Có thể bạn chưa đọc

Xem tất cả »

Đăng ký nhận bảng tin hàng tuần

Liên lạc trao đổi

Liên lạc thông qua Instagram

Thông qua Instagram, bạn có thể trao đổi trực tiếp và tức thời, cũng như cập nhật những thông tin mới nhất từ nhavantuonglai.

Tức thời

Bạn có thể gửi và nhận tin nhắn nhanh chóng, trực tiếp, giúp những vấn đề cá nhân của bạn được giải quyết tức thời và hiệu quả hơn.

Thân thiện

Vì tính chất là kênh liên lạc nhanh, nên bạn có thể bỏ qua những nghi thức giao tiếp thông thường, chỉ cần lịch sự và tôn trọng thì sẽ nhận được sự phản hồi đầy thân thiện, thoải mái từ tác giả.

Trao đổi trên email

Thông qua email cá nhân, bạn có thể trao đổi thỏa thuận hợp tác, kết nối chuyên sâu và mang tính chuyên nghiệp.

Tin cậy

Trong một số trường hợp, email được dùng như một tài liệu pháp lý, chính vì vậy mà bạn có thể an tâm và tin cậy khi trao đổi với tác giả thông qua email.

Chuyên nghiệp

Cấu trúc của email đặt tính chuyên nghiệp lên hàng đầu, nên những thông tin, nội dung được viết trong email từ tác giả sẽ luôn đảm bảo điều này ở mức cao nhất.

nhavantuonglai · Ghiblis Music Piano Playlist