Prime Number Array Program Question

This is my code thus far:

"def is_prime(num)
i = 2
while i < num.to_i
is_divisible = ((num % 1) == 0)

if is_divisible
  return false

i += 1



def prime(max)
primes_arr = []

q = 2
while q < max.to_i
if is_prime(q)
primes_arr << q

q += 1



class Object
def is_number?
self.to_i.to_s == self.to_s || self.to_f.to_s == self.to_s

puts 'This is a program that first determines whether a number is prime
or not, ’
puts ‘then displays an array of all prime numbers less than your given
puts ‘Part 1: Please enter a natural number greater than 1.’
num = gets.chomp

while num.to_i <= 1
puts ‘That’s not a natural number greater than 1, silly. Try again:’
num = gets.chomp

puts 'That your number is prime is ’ + is_prime(num).to_s + ‘.’
puts ‘’
puts ‘Part 2: Please enter a max number.’
max = gets.chomp

while max.is_number? == false
puts ‘That’s not a number, silly.’
puts ‘Try again.’
max = gets.chomp
puts ‘’
puts ‘The prime numbers smaller than your max are: ’ +
prime(max).join(’, ') + ‘.’"

The first bit works, but the second bit (viz. the part that spits out
all prime numbers smaller than your “max”) always outputs (assuming one
has entered a number) either nothing, or 2.

Can anyone provide any insight as to why that is so? Thanks in advance

Anthony Chang wrote in post #1146846:

while i < num.to_i
is_divisible = ((num % 1) == 0)
Perhaps this is better: (num % i)

Your code seem like C code transcripted ruby !

Try functional style, by example:

p=(2…num).each_with_object([]) { |x,prims| ( prims << x ) unless
prims.any? {|prim| x%prim ==0 } }

Thanks raubarede :]

There is another problem I’m just now realizing: the first part that
tests whether a number is prime or not always returns true.

I transplanted the is_prime(num) method to its own file, and ran that
extensively. It works then (as it should).

Not sure what’s going on…

Edit: should mention that the second bit does now return an array of all
prime numbers below the given max. It’s just the first bit that’s not

Can you imagine how many numbers pass this test?

is_divisible = ((num % 1) == 0)

Modulo 1 is nonsense.

Also, you can at least increment numbers by two because you know every
other number is divisible by 2.

I’d also cache all prime numbers for faster checking of multiple

And you should stop comparing values with true and false. This is error
prone. In Ruby nil and false mean “false” - everything else is “true”.
Just use boolean logic. If you want to test for falseness either use
negation or use “until” instead of “while” and “unless” instead of “if”.

Another thing: in your loop in is_prime you only need to iterate while
i*i < num.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs