Home > database >  How can I find the prime numbers between 1 to the given number, only by using the loop(ie. without a
How can I find the prime numbers between 1 to the given number, only by using the loop(ie. without a

Time:08-19

Kindly help me to find the prime numbers within the given number(ie: 1..n) without using any short cuts. use only the loops in Ruby

puts "Enter the number to find the prime number within the number: "
n = gets.chomp.to_i
num = []
prime = [2]
not_prime = []

for i in 2..n 
   num.push i 
end 

print "We are going to seperate the prime numbers and non prime numbers from the elements present in this array: #{num}"
puts "\n\n"

for i in num 
  (2..i-1).each do |x|
    if i % x == 0
      not_prime.push i
      # break 
    else 
    prime.push i
      # break
  end 
  end 
end 
print "The prime numbers are: #{prime}" 
puts "\n"
print "The non-prime numbers are: #{not_prime}"

CodePudding user response:

This does feel a lot like a school project/task rather than anything meaningful. There are libraries built into Ruby that you can use for high performance Prime calculations

puts "Enter the maximum number of the range in which to find the prime numbers: "
last = gets.chomp.to_i
prime = [2]
all_numbers = (2..last).to_a

print "We are going to separate the prime numbers and non prime numbers from the elements present in this array: #{all_numbers}\n\n"

all_numbers.each do |i|
  prime.push i unless prime.any? { |x| i % x == 0 }
end

print "The prime numbers are: #{prime}\n\n" 
print "The non-prime numbers are: #{all_numbers - prime}\n"
  • Related