Crea sito

Ruby | How to print Prime Numbers

I will show you quickly how to find and print a N amount of Prime Numbers in Ruby .

Here’s the code:

def prime(n)
  for i in 1...(n)
	isPrime = true
	for j in 2...(i)
		if i % j == 0
			isPrime = false
			break
		end
	end
	if isPrime
		puts i
	end
   end
end

prime(100)

This algorithm has a worst case asymptotic complexity of O(n^2)

For any question or suggestion feel free to comment this article below 🙂