How do I generate the first n prime numbers?

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

    I did this for a coding kata and used the Sieve of Eratosthenes.

    puts "Up to which number should I look for prime numbers?"
    number = $stdin.gets.chomp
    n = number.to_i
    array = (1..n).to_a
    
      i = 0
    
    while array[i]**2 < n
    
    i = i + 1
    array = array.select do |element|
      element % array[i] != 0 || element / array[i] == 1
    
    
    end
    end
    
     puts array.drop(1)
    

提交回复
热议问题