balee1991
balee1991

Reputation: 31

Prime numbers without definitions and classes, just loops

I am trying to input any number and check for prime numbers. I am trying to avoid classes and definitions. I am trying to use loops only. My code is listed below.

puts "What number would you like to find the largest prime factor?: "
lastnum = gets.to_i
puts "Number to find the largest prime factor is #{lastnum}"
n = 2
while (n <= lastnum)
  if n % 2 == 0
    puts "#{n} is not a prime"
  elsif n % Math.sqrt(n) == 0
    puts "#{n} is not a prime, sqrt rooted"
  else
    puts "#{n} is a prime"
  end
  n += 1
end

I get numbers such as 99 in my list of primes if I input 100. Is there something I can add to or remove from my code? If there is an efficient way and I should get away from what I am doing, I shall consider that help as well.

Upvotes: 0

Views: 131

Answers (2)

Abhishek28
Abhishek28

Reputation: 57

Enter the highest range, upto you want to find highest prime no.

lastnum = 100
(1..lastnum).reverse_each do |num|
   if (2..num/2).none?{|i| num % i == 0}
     puts num
     break
   end
end

Here, we get highest range in lastnum var, we check for prime no. in descending order ( here 100 to 1 ) and divide that no. from 2 to half of that no. Whenever we get our first prime no. (highest) we stop our condition loop and return that highest prime number.

Upvotes: 0

max pleaner
max pleaner

Reputation: 26778

Here is a largest_primes script without using methods.

input = 100
result = 2.upto(input - 1).select do |test_num|
  2.upto(test_num - 1).none? do |test_divider|
    (test_num % test_divider).zero?
  end
end.max

puts result
# => 97

Upvotes: 1

Related Questions