How do I generate the first n prime numbers?

前端 未结 15 1683
再見小時候
再見小時候 2021-02-02 09:57

I am learning Ruby and doing some math stuff. One of the things I want to do is generate prime numbers.

I want to generate the first ten prime numbers and the first ten

15条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-02 10:42

    Implemented the Sieve of Eratosthene (more or less)

    def primes(size)
        arr=(0..size).to_a
        arr[0]=nil
        arr[1]=nil
        max=size
        (size/2+1).times do |n|
            if(arr[n]!=nil) then
                cnt=2*n
                while cnt <= max do
                    arr[cnt]=nil
                    cnt+=n
                end
            end
        end
        arr.compact!
    end
    

    Moreover here is a one-liner I like a lot

    def primes_c a
        p=[];(2..a).each{|n| p.any?{|l|n%l==0}?nil:p.push(n)};p
    end
    

    Of course those will find the primes in the first n numbers, not the first n primes, but I think an adaptation won't require much effort.

提交回复
热议问题