Sieve of Eratosthenes in Ruby

前端 未结 5 1912
眼角桃花
眼角桃花 2020-12-14 20:10

Rather than scraping a Ruby version of this algorithm off the net I wanted to create my own based on its description here. However I cannot figure out two things

<         


        
5条回答
  •  Happy的楠姐
    2020-12-14 20:36

    This is a reference for those who are interested. The code is from this site.

    This code uses Sieve of Eratosthenes as well.

    n = 1000000
    ns = (n**0.5).to_i + 1
    is_prime = [false, false] + [true]*(n-1)
    2.upto(ns) do |i|
      next if !is_prime[i]
      (i*i).step(n, i) do |j|
        is_prime[j] = false
      end
    end
    
    count = 0
    list = (0..n).map do |i|
      count += 1 if is_prime[i]
      count
    end
    
    while gets
      puts list[$_.to_i]
    end
    

    And here is another one.

    def eratosthenes(n)
      nums = [nil, nil, *2..n]
      (2..Math.sqrt(n)).each do |i|
        (i**2..n).step(i){|m| nums[m] = nil}  if nums[i]
      end
      nums.compact
    end
    
    p eratosthenes(100)
    

提交回复
热议问题