Ruby - Prime Number calculator - ruby

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

i = 0
count = 0
loop do
if is_prime(i)
count += 1
end
if count == 10001
puts "#{i}"
break
end
end
Simple method :)

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.

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.

Related

Ruby- prime number unique and duplicates

I'm just learning Ruby :) and Im trying to create a simple prime-number program where all the primes of a number are printed.
I'm getting errors where the prime and nonprime numbers are mixed up
(ie: input of 9 will get you all nonprimes).
I'm sorry for such a beginner question - I'm struggling alot and need some help :)
puts "Enter a number please "
num = gets.chomp.to_i
i = 2
number = 2
while i < num
if number % i == 0
prime = false
end
i += 1
end
if prime == true
puts "#{number} is prime"
else
puts "#{number} is not prime"
end
number += 1
end
while i < num
if number % i == 0
prime = false
end
i += 1
end
# ...
It looks like that first end is meant to be an else.
It's easier to catch these things when you simplify your code, e.g. this method reduces to this (although there are other issues with it):
i = 2
number = 2
while i < num
(number % i).zero? ? prime = false : i += 1
puts "#{number} is #{'not ' unless prime}prime"
number += 1
end
End error is because of else
while i < num
if number % i == 0
prime = false
else
i += 1
end
if you have a short If - neater is writing it like:
if-condition ? 1 : 0
and in your case while is.. not the nicest choice - you should use range
(1...3).map{|x| puts(x) }
{} - allows multiline(with do end end)
this prints [1,2]
(1..3).map{|x| x*2 }
would be [2,4,9]
This should be enough hints of how to play around with your code without ruining the process.

Generate Random Numbers Until a certain

I am trying to write some code (using a while loop) that will generate random numbers (between 1 and 10) until the number 7 is generated.
Here is what I've got so far, but it's just stuck in a loop of printing random numbers between 1 and 10.
num = ""
while num != 7
print rand(1..10).to_s
end
puts "over"
I understand why it's looping without end, but I'm unsure of how else to generate the random numbers and still end the loop when a 7 appears.
There are many ways to do it, for example:
loop do
num = rand(1..10)
print num
break if num == 7
end
Also, to make your code work:
num = ""
while num != '7'
num = rand(1..10).to_s
print num
end
puts "over"
reason in that you convert num to string and compare it with integer
puts (number = rand(1..10)) until number == 7
The problem for this code is that you generate an infinite loop because num is always "", you need to update the variable num inside the while loop like this:
num = ""
while num != 7
num = rand(1..10)
puts num
end
puts "over"
in this case, you do not know when the loop will stop, but in each loop it can stop with probability 1/10, this is not a good practice, you nedd to know when the loop stops, so will be better to add a variable for maximum number of tries like this. And also you do not need to transform dthe number to string to print it:
num = 0
max_tries = 100
try = 1
guess = 7
while (try < max_tries && num != guess)
num = rand(1..10)
try = try + 1
puts num
end
if (try >= max_tries)
puts "you do not get the guess"
else
puts "over"
end
and you get this:
[4] pry(main)> 9
9
3
4
9
6
9
8
4
5
9
10
4
3
7
over
=> true
Try this out
$num = 0
while $num != 7
$num = rand(1..10)
print $num.to_s + "\n"
end
puts "over"
You have to assign the rand generated value into num variable,
$ num = ''
$ while num != 7
$ num = rand(1..10)
$ print num
$ end
$ # 6168510267=> nil

NoMethodError with .chr.to_i

I'm trying to create a recursive method sum_of_digits(i) that takes the sum of integers, i.e. '456' = 4+5+6 = 15
However, I receive a NoMethodError for chr.to_i in the following code:
def sum_of_digits(i)
input = i.to_s
if i == 0
return 0
elsif input.length == 1
return i
else
for n in 1..input.length
sum += input[i].chr.to_i % 10^(n-1)
end
end
return sum
end
Thank you!
String indexes are zero-based in ruby. The problem is here:
for n in 1..input.length
it should be written as
for n in 0..input.length-1
BTW, call to chr is superfluous as well, since you already have a string representation of a digit there. As well, sum must be declared in advance and set to zero.
Also, the whole code is not ruby idiomatic: one should avoid using unnecessary returns and for-loop. The modified version (just in case) would be:
def sum_of_digits(i)
input = i.to_s
case
when i == 0 then 0 # return zero
when input.length == 1 then i # return i
else
sum = 0
input.length.times do |index|
sum += input[index].to_i % 10^index
end
sum
end
end
or, even better, instead of
sum = 0
input.length.times do |index|
sum += input[index].to_i % 10^index
end
sum
one might use inject:
input.length.times.inject(0) do |sum, index|
sum += input[index].to_i % 10^index
end

Finding a prime number using a **custom** Ruby method

I would like to pass an array of numbers to my is_prime? method and return if the numbers are valid or not. I do not want to use:
require 'prime'
a = [1,2,3,4,5]
Hash[a.zip(a.map(&Prime.method(:prime?)))]
This is learning experience. My current code is only outputing the first number in the array. Can someone help me understand what I am doing wrong? Thanks!
def is_prime?(*nums)
i = 2
nums.each do |num|
while i < num
is_divisible = ((num % i) == 0)
if is_divisible == false
x = "#{num}: is NOT a prime number." #false
else
x = "#{num}: is a prime number." #true
end
i +=1
end
return x
end
end
puts is_prime?(27,13,42)
You are returning in the loop.
A few bugs in your method:
def is_prime?(*nums)
nums.each do |num|
return false if num == 1
next if num == 2 # 2 is the only even prime
i = 2 # needs to be reset for each num
while i < num
return false if num % i == 0 # num is not prime
i += 1
end
end
true # We'll reach here only if all the numbers are prime
end
This will return your results in the same format as your usage of the prime library with the same logic as your custom function:
def is_prime?(*nums)
nums.each_with_object({}) do |num, hsh|
hsh[num] = num > 1 && 2.upto(num - 1).none? { |i| num % i == 0 }
end
end
puts is_prime?(27,13,42)
# => {27=>false, 13=>true, 42=>false}
Since you mention this is just for learning, I'm assuming you know that a sieve is a better way to go for this than brute force iteration.
If you want an explanation of how the above code works or further help understanding why your current code doesn't, let me know in the comments.

Evaluating exit condition at bottom of Ruby while loop

I have a very basic question about Ruby loops.
This program as written returns the ith prime number +1 (ie the example should return 17). I know I could simply return cand-1, but I was wondering what the "Ruby way" of checking if the answer has been found at the bottom of the while loop and only incrementing if it hasn't.
def ith_prime(i)
pI = 0 # primes index
divs = []
cand = 2
until pI == i do
if divs.find { |div| cand%div == 0 } == nil
divs << cand
pI += 1
end
cand += 1
end
cand
end
puts ith_prime(7)
> 18
I use loop instead of while or until most of the time. This way I can put the exit condition anywhere in the loop.
I would write it like that (if I understood the problem correctly):
def ith_prime(i)
pI = 0 # primes index
divs = []
cand = 2
loop do
unless divs.find { |div| cand%div == 0 }
divs << cand
pI += 1
end
break if pI == i
cand += 1
end
cand
end

Resources