How do I generate the first n prime numbers?

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

    Ruby: Print N prime Numbers http://mishra-vishal.blogspot.in/2013/07/include-math-def-printnprimenumbernoofp.html

    include Math
    
    def print_n_prime_number(no_of_primes=nil)
    
      no_of_primes = 100 if no_of_primes.nil?
    
      puts "1 \n2"
    
      count = 1
    
      number = 3
    
      while count < no_of_primes
    
    sq_rt_of_num = Math.sqrt(number)
    
    number_divisible_by = 2
    
    while number_divisible_by <= sq_rt_of_num
    
      break if(number % number_divisible_by == 0)
    
      number_divisible_by = number_divisible_by + 1
    
    end
    
    if number_divisible_by > sq_rt_of_num
    
      puts number
    
      count = count+1
    
    end
    
    number = number + 2
    
      end
    
    end
    
    print_n_prime_number
    

提交回复
热议问题