Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate the first n prime numbers?

Tags:

ruby

primes

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 only. I have no problem testing a number to see if it is a prime number or not, but was wondering what the best way is to do generate these numbers?

I am using the following method to determine if the number is prime:

class Integer < Numeric   def is_prime?     return false if self <= 1     2.upto(Math.sqrt(self).to_i) do |x|       return false if self%x == 0     end     true   end end 
like image 279
Tony Petley Avatar asked Jul 26 '12 16:07

Tony Petley


People also ask

Is there a formula to generate prime numbers?

Methods to Find Prime Numbers Two consecutive numbers which are natural numbers and prime numbers are 2 and 3. Apart from 2 and 3, every prime number can be written in the form of 6n + 1 or 6n – 1, where n is a natural number. Note: These both are the general formula to find the prime numbers.

What is first n prime number?

The prime numbers from 1 to 100 are: 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.

How do you find the n prime number?

An easy way to determine if a number is prime is by trial division: divide the number n by all the integers less than n, and if no exact divisors–other than 1–are found, then n is prime.

How do you find first n prime numbers in C++?

Find the Product of first N Prime Numbers in C++ We have to find the product of prime numbers between 1 to n. So if n = 7, then output will be 210, as 2 * 3 * 5 * 7 = 210. We will use the Sieve of Eratosthenes method to find all primes. Then calculate the product of them.


1 Answers

In Ruby 1.9 there is a Prime class you can use to generate prime numbers, or to test if a number is prime:

require 'prime'  Prime.take(10) #=> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] Prime.take_while {|p| p < 10 } #=> [2, 3, 5, 7] Prime.prime?(19) #=> true 

Prime implements the each method and includes the Enumerable module, so you can do all sorts of fun stuff like filtering, mapping, and so on.

like image 95
Scott Olson Avatar answered Sep 17 '22 22:09

Scott Olson