How do I generate the first n prime numbers?

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

    I think this may be an expensive solution for very large max numbers but seems to work well otherwise:

    def multiples array
      target = array.shift 
      array.map{|item| item if target % item == 0}.compact
    end
    
    def prime? number
      reversed_range_array = *(2..number).reverse_each
      multiples_of_number = multiples(reversed_range_array)
      multiples_of_number.size == 0 ? true : false
    end
    
    def primes_in_range max_number
      range_array = *(2..max_number)
      range_array.map{|number| number if prime?(number)}.compact
    end
    

提交回复
热议问题