Reputation: 663
I just started getting my hands dirty on ruby and was wondering if someone can help me with this array of primes example. I got the problem off of project Euler, and I want ruby to print an array of prime numbers. However, every time I run the program, it outputs just "0". Can someone shed some light here. Thank you in advance.
def prime
x = 13195
count = 0
a = [ ]
while count < x
if count % x == 0
a.push(count)
a.sort
end
count += 1
end
puts a
end
Upvotes: 0
Views: 400
Reputation: 59651
Assuming you want to test if 13195
is a prime, and you want a
to keep a list of which numbers divide into 13195
You need to start count
at 2, since every number including a prime is divisible by 1. You also need to use x % count
instead of count % x
. x % count
divides x by count and gives you the remainder (which are correctly checking against 0 for).
def prime
x = 13195
count = 2
a = [ ]
while count < x
if x % count == 0
a.push(count)
end
count += 1
end
a
end
arr = prime
p arr #this will print out a list of numbers which fit into 13195
arr.size == 0 #true if number is a prime, false otherwise
Note that there is a lot of optimizations you can do in this algorithm to check if a number is a prime - namely your for loop condition can be:
sqrt = Math.sqrt(x)
while count < sqrt
you only need to check up to the square root of your number to see if it's a prime
Upvotes: 1
Reputation: 17866
Your array is 0 because count
is always less than x
, so dividing count
by x
, as the modulus operator does, always returns 0.
Your variable count
is poorly named; I would call it f
for factor. And it should be initialized to 2, not 0. Your modulus operator is reversed; it chouls be x % f
instead of the other way around. And your while
loop should stop as soon as f * f > x
, since at that point the remaining x
must be prime.
Upvotes: 0