How do I generate the first n prime numbers?

前端 未结 15 1682
再見小時候
再見小時候 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:33

    Here is a way to generate the prime numbers up to a "max" argument from scratch, without using Prime or Math. Let me know what you think.

    def prime_test max
        primes = []
        (1..max).each {|num| 
            if
                (2..num-1).all? {|denom| num%denom >0}
            then
                primes.push(num)
            end
        }
        puts primes
    end
    
    prime_test #enter max
    

提交回复
热议问题