Trying to figure out if user input is prime or not with ruby - ruby

I am new to Ruby and just read about methods and such I have been working on a program in order to get the user to type in a number and determine if it is prime or not. This is what I have so far.
print "Enter a number: "
num = gets.chomp
def prime(n)
factors = []
if num < 2
puts "#{num} is a prime number"
end
while n % num == 0 and num < n
factors.push(num)
num += 1
end
return factors
end
Not even sure if I'm on the right track. Really lost. Any help would be greatly appreciated!

require 'prime'
print "Enter a number: "
num = gets.chomp
Prime.prime?(n)
Or, from the scratch:
def prime?(n)
if n > 1
min_condition = Math.sqrt(n).to_i # The highest factor is necessary at most sqrt(n)
factors = 0
(1..min_condition).step(2).each do |i| # It's not necessary to check even numbers
factors += 1 if (n.to_f / i) % 1 == 0
break if factors > 1 # If the algorithm find 2 factors, the number isn't prime
end
!(factors > 1)
else
false
end
end

I know that you're doing this to learn Ruby, but keep in mind that you can just use Prime.prime? to determine whether or not a number is prime.
require 'prime'
Prime.prime?(3)
#=> true
Prime.prime?(4)
#=> false
As for your actual problem, you use both num and n inside your method, but num is defined outside, so won't be in scope. Also: you never seem to actually be calling prime.

There are some problems with your program:
You want to get the user to type in a number and determine if it is
prime or not but the output of your method prime doesn't answer
this question. It will return an array.
If a number is less then 2, it is not a prime number (wikipedia), so this piece of your code is wrong:
if num < 2
puts "#{num} is a prime number"
end
There are plenty of ways to check if a number is a prime number or not, this topic may help you to implement with Ruby.

If you don't want to use ruby base library than below code is useful for you
print "Enter a number: "
num = gets.chomp
def check_prime_number(num)
num = num.to_i
n = 1
factors = []
while (num >= n ) do
if (num % n == 0 )
factors << n unless factors.include?(n)
end
n += 1
end
if ( factors.size > 2)
puts "Factors of number #{num} :-> #{factors}"
elsif num > 0
puts "#{num} is prime"
end
end
check_prime_number(num)
Try if its helpful for you.

Related

Generally Fizzy ruby

Given the following variables
divisor_array, low, high define a method that
Prints all numbers from low to high
If the any number being printed is divisible by any divisor number in divisor_array, print the number + the word "fizzy"
If the number being printed is divisible by ALL the numbers in the array, it should output the number + "reallyfizzy".
Testing Values: generally_fizzy([2,3],1,7)
My initial solution:
def generally_fizzy(divisor_array, low, high)
divisors = Hash[*divisor_array]
low.upto(high) do |i|
divisors.each_pair do |k,v|
if((i % k == 0) && (i % v == 0))
puts "#{i} reallyfizzy"
elsif ((i % k == 0) || (i % v == 0))
puts "#{i} fizzy"
else
puts i
end
end
end
end
this solution passes the tests given, but when the divisor_array size is increased from 2 values to 3 and over it prints out duplicates. In addition to that, the code is not very elegant.
Looking for a working alternative, that can deal with divisor_array size changes.
Just count how many divisors in the array will divide the value. There are three cases we care about:
all of them
at least one of them
none of them.
def fizzy(divisors, lo, hi)
lo.upto(hi) do |value|
puts case divisors.count{ |div| value % div == 0 }
when divisors.length # all divisors
"#{value} really fizzy"
when 0 # no divisors
value
else # at least one divisor
"#{value} fizzy"
end
end
end
this is a little bit modified answer. It uses one exit point from method which i find more readable and robust (can be optimized if performance is a concern).
def fizzy(divisors, low, high)
low.upto(high) do |value|
print "#{value} "
print "really" unless divisors.detect{ |div| value % div != 0}
print "fizzy" if divisors.detect{ |div| value % div == 0}
print "\n"
end
end
fizzy([2,3],1,7) #=>
1
2 fizzy
3 fizzy
4 fizzy
5
6 reallyfizzy
7

Ruby coding: List out all factors of numbers from 1-100

Write a function that prints out all the factors for each of the numbers 1 through 100.
Really amateur coder but here's my attempt so far.
def factors_numbers(n1,n2)
(n1..n2).each do |n|
factors = []
factors << 1 ##every number has a factor of 1
factors << n ##every number is a factor of itself
i = 1
while i < n
new_number = n % (n-i)
if new_number == 0 #if 0, divisible and that means two numbers are factors
factors << new_number
factors << (n-i)
end
i += 1
end
return factors
end
end
Here is an improved version of your code:
def factors_numbers(n1,n2)
all_factors = {}
(n1..n2).each do |n|
factors = []
(1..Math.sqrt(n).floor).each do |i|
remainder = n % i
if remainder == 0 #if 0, divisible and that means two numbers are factors
factors << i
factors << n/i
end
end
factors = factors.sort.uniq
puts "Factors of #{n}: #{factors.join(',')}"
all_factors[n]=[factors]
end
return all_factors
end
Do you want unique factors? That is, in the range 1-100, should I get the number 1 a hundred times, or only once?
The easiest way to do this is by leveraging the "inject" Enumerable method.
def find_all_factors_between(n1,n2)
(n1..n2).inject([]) do |factors, num|
factors + (1..num).inject([]) { |arry, test| num % test == 0 ? arry + [test] : arry }
end
end
One final thing to note is that Ruby has implicit returns; that is, as long as the output of the last line of your method is your factors variable, you don't have to say return factors.
And my entry would be:
def find_all_factors_between(n1, n2)
factors = -> (n) { (1..n).select {|i| n % i == 0} }
(n1..n2).each { |n| puts "Factors of #{n}: #{factors.(n).join(', ')}" }
end
find_all_factors_between(1,100)
Well, if you wanted to do it with enumerables, there's always
def factor_numbers(rng)
factors = rng.map do |n|
(1..Math.sqrt(n).floor) # search numbers <= square root
.select { |d| n % d == 0 } # find factors <= square root
.flat_map { |x| [x, n / x] } # combine with factors >= square root
.sort # order from least to greatest
.uniq # remove dupes (basically the square root)
end
Hash[rng.zip(factors)] # rng = keys, factors = values
end
puts factor_numbers(1..100)
It's not the most efficient, but my point is just that many of the for/while constructs you'd see in languages like C or JavaScript can be expressed in other ways in Ruby.
(n1..n2).each{|x| print "#{x}: #{(1..x).select{|y| x % y == 0}}\n"}
That oughta do it :)
edit: Implemented Cary Swoveland's suggestion
def factor_nums(n1,n2)
all_factors = {}
(n1..n2).each do |n|
factors = []
(1..n).each do |i|
remainder = n % i
factors << i if remainder == 0
end
all_factors[n] = factors
end
return all_factors
end

How do I generate the first n prime numbers?

I am learning Ruby and doing some math stuff. One of the things I want to do is generate prime numbers.
I want to generate the first ten prime numbers and the first ten only. I have no problem testing a number to see if it is a prime number or not, but was wondering what the best way is to do generate these numbers?
I am using the following method to determine if the number is prime:
class Integer < Numeric
def is_prime?
return false if self <= 1
2.upto(Math.sqrt(self).to_i) do |x|
return false if self%x == 0
end
true
end
end
In Ruby 1.9 there is a Prime class you can use to generate prime numbers, or to test if a number is prime:
require 'prime'
Prime.take(10) #=> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
Prime.take_while {|p| p < 10 } #=> [2, 3, 5, 7]
Prime.prime?(19) #=> true
Prime implements the each method and includes the Enumerable module, so you can do all sorts of fun stuff like filtering, mapping, and so on.
If you'd like to do it yourself, then something like this could work:
class Integer < Numeric
def is_prime?
return false if self <= 1
2.upto(Math.sqrt(self).to_i) do |x|
return false if self%x == 0
end
true
end
def next_prime
n = self+1
n = n + 1 until n.is_prime?
n
end
end
Now to get the first 10 primes:
e = Enumerator.new do |y|
n = 2
loop do
y << n
n = n.next_prime
end
end
primes = e.take 10
require 'prime'
Prime.first(10) # => [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
Check out Sieve of Eratosthenes. This is not Ruby specific but it is an algorithm to generate prime numbers. The idea behind this algorithm is that you have a list/array of numbers say
2..1000
You grab the first number, 2. Go through the list and eliminate everything that is divisible by 2. You will be left with everything that is not divisible by 2 other than 2 itself (e.g. [2,3,5,7,9,11...999]
Go to the next number, 3. And again, eliminate everything that you can divide by 3. Keep going until you reach the last number and you will get an array of prime numbers. Hope that helps.
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
People already mentioned the Prime class, which definitely would be the way to go. Someone also showed you how to use an Enumerator and I wanted to contribute a version using a Fiber (it uses your Integer#is_prime? method):
primes = Fiber.new do
Fiber.yield 2
value = 3
loop do
Fiber.yield value if value.is_prime?
value += 2
end
end
10.times { p primes.resume }
# First 10 Prime Numbers
number = 2
count = 1
while count < 10
j = 2
while j <= number
break if number%j == 0
j += 1
end
if j == number
puts number
count += 1
end
number += 1
end
Implemented the Sieve of Eratosthene (more or less)
def primes(size)
arr=(0..size).to_a
arr[0]=nil
arr[1]=nil
max=size
(size/2+1).times do |n|
if(arr[n]!=nil) then
cnt=2*n
while cnt <= max do
arr[cnt]=nil
cnt+=n
end
end
end
arr.compact!
end
Moreover here is a one-liner I like a lot
def primes_c a
p=[];(2..a).each{|n| p.any?{|l|n%l==0}?nil:p.push(n)};p
end
Of course those will find the primes in the first n numbers, not the first n primes, but I think an adaptation won't require much effort.
Here is a way to generate the prime numbers up to a "max" argument from scratch, without using Prime or Math. Let me know what you think.
def prime_test max
primes = []
(1..max).each {|num|
if
(2..num-1).all? {|denom| num%denom >0}
then
primes.push(num)
end
}
puts primes
end
prime_test #enter max
I think this may be an expensive solution for very large max numbers but seems to work well otherwise:
def multiples array
target = array.shift
array.map{|item| item if target % item == 0}.compact
end
def prime? number
reversed_range_array = *(2..number).reverse_each
multiples_of_number = multiples(reversed_range_array)
multiples_of_number.size == 0 ? true : false
end
def primes_in_range max_number
range_array = *(2..max_number)
range_array.map{|number| number if prime?(number)}.compact
end
class Numeric
def prime?
return self == 2 if self % 2 == 0
(3..Math.sqrt(self)).step(2) do |x|
return false if self % x == 0
end
true
end
end
With this, now 3.prime? returns true, and 6.prime? returns false.
Without going to the efforts to implement the sieve algorithm, time can still be saved quickly by only verifying divisibility until the square root, and skipping the odd numbers. Then, iterate through the numbers, checking for primeness.
Remember: human time > machine time.
I did this for a coding kata and used the Sieve of Eratosthenes.
puts "Up to which number should I look for prime numbers?"
number = $stdin.gets.chomp
n = number.to_i
array = (1..n).to_a
i = 0
while array[i]**2 < n
i = i + 1
array = array.select do |element|
element % array[i] != 0 || element / array[i] == 1
end
end
puts array.drop(1)
Ruby: Print N prime Numbers
http://mishra-vishal.blogspot.in/2013/07/include-math-def-printnprimenumbernoofp.html
include Math
def print_n_prime_number(no_of_primes=nil)
no_of_primes = 100 if no_of_primes.nil?
puts "1 \n2"
count = 1
number = 3
while count < no_of_primes
sq_rt_of_num = Math.sqrt(number)
number_divisible_by = 2
while number_divisible_by <= sq_rt_of_num
break if(number % number_divisible_by == 0)
number_divisible_by = number_divisible_by + 1
end
if number_divisible_by > sq_rt_of_num
puts number
count = count+1
end
number = number + 2
end
end
print_n_prime_number
Not related at all with the question itself, but FYI:
if someone doesn't want to keep generating prime numbers again and again (a.k.a. greedy resource saver)
or maybe you already know that you must to work with subsequent prime numbers in some way
other unknown and wonderful cases
Try with this snippet:
require 'prime'
for p in Prime::Generator23.new
# `p` brings subsequent prime numbers until the end of the days (or until your computer explodes)
# so here put your fabulous code
break if #.. I don't know, I suppose in some moment it should stop the loop
end
fp
If you need it, you also could use another more complex generators as Prime::TrialDivisionGenerator or Prime::EratosthenesGenerator. More info
Here's a super compact method that generates an array of primes with a single line of code.
def get_prime(up_to)
(2..up_to).select { |num| (2...num).all? { |div| (num % div).positive? } }
end
def get_prime(number)
(2..number).each do |no|
if (2..no-1).all? {|num| no % num > 0}
puts no
end
end
end
get_prime(100)

optimize this ruby code

So this code will count the total number of pairs of numbers whose difference is K. it is naive method and I need to optimize it. suggestions?
test = $stdin.readlines
input = test[0].split(" ")
numbers = test[1].split(" ")
N = input[0]
K = input[1]
count = 0
for i in numbers
current = i.to_i
numbers.shift
for j in numbers
difference = (j.to_i - current).abs
if (difference == K)
count += 1
end
end
end
puts count
Would have been nice for you to give some examples of input and output, but I think this is correct.
require 'set'
def count_diff(numbers, difference)
set = Set.new numbers
set.inject 0 do |count, num|
set.include?(num+difference) ? count+1 : count
end
end
difference = gets.split[1].to_i
numbers = gets.split.map { |num| num.to_i }
puts count_diff(numbers, difference)
Untested, hopefully actual Ruby code
Documentation for Set: http://www.ruby-doc.org/stdlib/libdoc/set/rdoc/classes/Set.html
require 'set'
numbers_set = Set.new
npairs = 0
numbers.each do |number|
if numbers_set.include?(number + K)
npairs += 1
end
if numbers_set.include?(number - K)
npairs += 1
end
numbers_set.add(number)
end
Someone deleted his post, or his post was deleted... He had the best solution, here it is :
test = $stdin.readlines
input = test[0].split(" ")
numbers = test[1].split(" ")
K = input[1]
count = 0
numbers.combination(2){|couple| couple.inject(:-).abs == K ? count++}
puts count
You don't even need N.
I do not know Ruby so I'll just give you the big idea:
Get the list
Keep a boolean array (call it arr), marking off numbers as true if the number exists in the list
Loop through the list and see if arr[num-K] and/or arr[num+K] is true where num is a number in your list
This uses up quite a bit of memory though so another method is to do the following:
Keep a hash map from an integer n to an integer count
Go through your list, adding num+K and num-K to the hash map, incrementing count accordingly
Go through your list and see if num is in the hash map. If it is, increment your counter by count

Ruby - determine if a number is a prime

I'm running through the problems on Project Euler to teach myself Ruby programming. I know there is a built-in function to do this, but I'm avoiding the built-in functions to help me learn.
So I have to write a method to determine if a number is a prime. The first method works, but the second doesn't. Can anyone explain why?
def is_prime n
for d in 2..(n - 1)
if (n % d) == 0
return false
end
end
true
end
def is_prime2 n
foundDivider = false
for d in 2..(n - 1)
foundDivider = ((n % d) == 0) or foundDivider
end
not foundDivider
end
It's because = is of higher precedence than or. See Ruby's operator precedence table below (highest to lowest precedence):
[ ] [ ]=
**
! ~ + -
* / %
+ -
>> <<
&
^ |
<= < > >=
<=> == === != =~ !~
&&
||
.. ...
? :
= %= { /= -= += |= &= >>= <<= *= &&= ||= **=
defined?
not
or and
if unless while until
begin/end
The problematic line is being parsed as...
(foundDivider = ((n % d) == 0)) or foundDivider
...which is certainly not what you mean. There are two possible solutions:
Force the precedence to be what you really mean...
foundDivider = (((n % d) == 0) or foundDivider)
...or use the || operator instead, which has higher precedence than =:
foundDivider = ((n % d) == 0) || foundDivider
Ruby comes with predefined classes such as Prime. All you have to do is to require that class into your project.
require 'prime'
Than, you can use some of the Prime methods such as first to get first x prime elements:
Prime.first(5) # Ret => [2, 3, 5, 6, 11]
Or you could do something like this:
Prime.each(100) do |prime|
p prime # Ret => [2, 3, 5, 7, 11, ..., 97]
end
I hope you find this useful.
def prime(n)
return false if n < 2
(2..n/2).none?{|i| n % i == 0}
end
A prime number is any number that has no positive divisors other than itself and 1.
def prime? n
(2..Math.sqrt(n)).none? {|f| n % f == 0}
end
The range of factors should start at 2 and end at the square root of n because every number is divisible by one and no number is divisible by two numbers greater than its square root.
Explanation: A non-prime number is the product of two numbers.
n = f1 * f2
n is always divisible by its square root so both f1 and f2 cannot be greater than the square root of n, otherwise f1 * f2 would be greater than n. Therefore, at least one factor is less than or at most equal to Math.sqrt(n). In the case of finding prime numbers its only necessary to find one factor so we should loop from 2 to the square root of n.
Find prime numbers from loop:
def get_prime_no_upto(number)
pre = [1]
start = 2
primes = (start..number).to_a
(start..number).each do |no|
(start..no).each do |num|
if ( no % num == 0) && num != no
primes.delete(no)
break
end
end
end
pre + primes
end
and use it as below:
puts get_prime_no_upto(100)
Cheers!
Here is code that will prompt you to enter a number for prime check:
puts "welcome to prime number check"
puts "enter number for check: "
n = gets
n = n.to_i
def prime(n)
puts "That's not an integer." unless n.is_a? Integer
is_prime = true
for i in 2..n-1
if n % i == 0
is_prime = false
end
end
if is_prime
puts "#{n} is prime!"
else
puts "#{n} is not prime."
end
end
prime(n)
Based on the answer by Darmouse but including edge cases
def prime? (n)
if n <= 1
false
elsif n == 2
true
else
(2..n/2).none? { |i| n % i == 0}
end
end
FYI - re: DarkMouses prime method above - I found it really helpful, but there are a few errors (I think!) that need explaining:
It should be parentheses rather than square brackets... Otherwise you get a TypeError
Range can't be coerced into Fixnum (TypeError)
Secondly, that first colon before 'false' would cause an error too. It's incorrect syntax, as far as I know. Get rid of it.
Lastly, I think you got it the wrong way round?? If you correct the errors I mentioned, it returns true if it ISN'T a prime, and false if it IS.
You can drop the ternary operator altogether I think, and just do:
def prime?(n)
(2..n/2).none?{|i| n % i == 0}
end
Obviously it doesn't cover the edge cases (0,1,2), but let's not split hairs.
...For those who enjoy hairsplitting, here is my full solution to this problem:
def prime?(n)
return false if n < 2
(2..Math.sqrt(n)).none? {|num| length % num == 0}
end
Hope I didn't miss anything :)
This is a little bit off topic according to the details, but correct for the title : using bash integration in ruby you could do :
def is_prime n
`factor #{n}`.split.count < 3
end
bash factor function returns a number plus all of his factors, so if the number is prime, there will be two words count.
This is usefull for code golf only.
I tried this and it worked:
def prime?(n)
return false if n < 2
return true if n == 3 || n == 2
if (2...n-1).any?{|i| n % i == 0}
false
else
true
end
end
def prime?(n)
if n <= 1
return false
else (2..n-1).to_a.all? do |integer|
n % integer != 0
end
end
end
From my prime? lab. Started with eliminating all integers less than or equal to 1.
def prime(n)
pn = [2]
if n < 2
return false
else
(2..n).each do |i|
not_prime = false
(2..Math.sqrt(i).ceil).each do |j|
not_prime = true if i % j == 0
end
pn.push(i) unless not_prime
end
end
return pn
end
p prime(30) gives
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
It will return true if the number is prime.
def prime_number(number)
(2..(number-1)).each do |value|
if (number % value) == 0
return false
end
return true
end
end
puts prime_number(4)
class Object
private
def prime? num
if (2..3).include? num
return true
else
!num.even? and num % 3 != 0 and num > 1
end
end
end
prime? 1
prime? 2
prime? 9
prime? 17
** FOR A SIMPLE SHORTED METHOD**
FIRST INSTALL PRIME GEM
require 'prime'
`p prime.first(20)`
Now save that file as your desired name, this will generate the first 20 prime numbers Automatically!! :-)

Resources