List of prime numbers using Array methods

后端 未结 3 832
余生分开走
余生分开走 2021-01-15 17:35

I have a code to get list of prime numbers:

def primes_numbers num
    primes = [2]

    3.step(Math.sqrt(num) + 1, 2) do |i|
        is_prime = true     

          


        
相关标签:
3条回答
  • 2021-01-15 18:17

    Features : Check a number is Prime, get a number factors and get list of prime numbers and also you can easily transform it in any language you want

    As Ruby has its own Prime class so you don't need to worry

    but if you want to do it your own without using ruby core things

    n=100 #=> a
    
    def prime_numbers(n)
      prime_numbers = []
      (1..n).each do |number|
          prime_numbers << number if is_prime(number)
      end
      prime_numbers
    end
    
    def is_prime(n)
       if factors(n).count > 2
          return true
       end
       return false
    end
    

    # find factors of a number

    def factors(n)
         factors = []
         (1..n).each {|d| factors << d if (n%d).zero?}
         factors
    end
    

    Note: There are three functions involved and I deliberately do this for beginners, So that they can easily understand about it

    Optimization Guide:

    1) You can start loop from 2 and end at n-1 if you want to save iterations

    2) use Ruby core functions and enjoy things :)

    0 讨论(0)
  • 2021-01-15 18:24

    You can list prime numbers like this as well.

    Example Array: ar = (2..30).to_a
    ar.select{ |n| (2..n).count{ |d| (n % d).zero? } == 1 }
    
    0 讨论(0)
  • 2021-01-15 18:25

    Ruby 1.9 has a very nice Prime class:

    http://www.ruby-doc.org/core-1.9/classes/Prime.html

    But I'm assuming you don't care about any standard classes, but want to see some code, so here we go:

    >> n = 100 #=> 100
    >> s = (2..n) #=> 2..100
    >> s.select { |num| (2..Math.sqrt(num)).none? { |d| (num % d).zero? }} 
    #=> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
    

    Note: I wrote it this way because you wanted Enumerable methods, for efficiency's sake you probably want to read up on prime finding methods.

    0 讨论(0)
提交回复
热议问题