JDillon522
JDillon522

Reputation: 19666

Ruby - Prime Number calculator

I need some feedback to figure out why I cant puts or print anything from my methods on the screen. This is a simple script I wrote to solve the problem of finding the 1001st prime number. Thanks

def primes
  # iterates through numbers until it has the 1001th prime number and returns it.
  # I chose to create the num_primes variable instead of counting the number of 
  # elements in in_prime_array every iteration
  # based upon a guess that it would be faster to check.

is_prime_array = []
  num_primes = 0
  i = 2
  loop do
    is_prime_array << i && num_primes += 1 if is_prime?(i) == true 
    i += 1
    break if num_primes == 1001
    end
  is_prime_array[1001]
end


def is_prime? (num)
# Checks to see if the individual number given is a prime number or not.
i = 2
  loop do
    if i == num
      return true
    elsif num % i == 0
      return false
    else
      i += 1
    end
  end
end

Thanks for any help!


EDIT


I took your advice and tried this pice of code:

def is_prime? (num)
  # Checks to see if the individual number given is a prime number or not.
  i = 2
  loop do
    if i == num
      return true
    elsif num % i == 0
      return false
    else
      i += 1
    end
  end
end

i = 0
count = 0
loop do
  count += 1 if is_prime?(x)
  puts "#{i}" if count == 1001
  break
end

It still returns nothing. Hummm

Upvotes: 2

Views: 2108

Answers (3)

Kiattisak Anoochitarom
Kiattisak Anoochitarom

Reputation: 2157

i = 0
count = 0
loop do
  if is_prime(i)
    count += 1
  end

  if count == 10001
    puts "#{i}"
    break
  end
end

Simple method :)

Upvotes: 2

ben_makes_stuff
ben_makes_stuff

Reputation: 518

What are you trying to "puts"? The first thing I notice is that there is no call to primes in the file, so nothing will happen if you try to run this code by itself. Maybe that's why you don't see anything printed.

Here's an example of how to print a few variables inside your loop:

loop do
  ...
  puts "At iteration #{i}, we have prime=#{is_prime?(i)}"

If you don't know, enclosing a statement with #{<statement goes here>} inside a string is the same as appending the return value of <statement goes here> to the string at that position. This is the same as "Str " + blah + " rest of str" in a language like Java.

Upvotes: 1

Neil Slater
Neil Slater

Reputation: 27207

It's an off-by-one error. If you have 1001 elements in an array, the last element will be at index 1000.

Where you have

is_prime_array[1001]

Change it to

is_prime_array[1000]

And you can do this:

puts primes
 => 7927

You could also have

is_prime_array.last

instead of a specific index number.

Upvotes: 1

Related Questions