Function with arguments (prime numbers) - ruby

I want a ruby program, it have 2 Arguments(a,b) ,which output the Prime
numbers between a and b. here is my program. but it's wrong. i don't know
where is the problem. can anyone help me?
a,b=ARGV
def prime (a,b)
for i in 2..b
f=true
for p in 2...i
if i%p==0
f =!f
break
end
end
print i, "--" if f
end
end
sushu=prime(a,b)
p "the prime zweischen #{a} and #{b} is #{sushu}."

The other answers already pointed out what is wrong with your code (using strings instead of integers and not using the argument a. However, if you are on Ruby 1.9, there's a much easier way to achieve what you want:
require 'prime'
def prime(a, b)
(a..b).select(&:prime?)
end
prime(1,20)
#=> [2, 3, 5, 7, 11, 13, 17, 19]

You do not consider the in parameter a. Probably changing i to iterate from a..b, instead of ..b will fix your problem.
a,b=ARGV
def prime (a,b)
for i in a..b
f=true
for p in 2...i
if i%p==0
f =!f
break
end
end
print i, "--" if f
end
end
sushu=prime(a,b)
p "the prime zweischen #{a} and #{b} is #{sushu}."

Try
sushu=prime(a.to_i,b.to_i)

Related

Trying to solve for the largest prime factor without recursion - Ruby

I came across a website called Project Euler and everything was going well until I hit the 3rd problem - The Largest Prime Factor. I don't want to use recursion to solve it. I saw solutions online where they use Math.sqrt and I don't want to use that either. Stubborn, I know.
I'd like to solve it with just loops and if statements. I assumed the input is an odd number. Here is my code. The output keeps coming out as [3] if num = 99 and I can't figure out why. I tried putting a puts statement everywhere to see what was being outputted at each step. One issue I realized was that that the array#p was not resetting after each loop. I tried array.clear but that wasn't much help. Could someone point me in the right direction? Is there some fundamental aspect about arrays, loops, and if-statements that I'm not getting?
def prime(num)
arr = []
p = []
not_p = []
# first I find all the numbers that num is divisible by
for i in (2..num/2)
if num % i == 0
arr << i
end
end # this should output [3, 9, 11, 33]
arr.each do |x| # I loop through each element in the above array
for i in (2..(x/2)) # I divide each element - x - by 2 because it cannot be divisble by anything greater than its half
if x % i == 0 # if x is divisble by i
not_p << i # I push the i into array#not_p
end # keep looping until i reaches x/2
end
if not_p.length == 0 # if there are no values in array#not_p, then I know x is a prime factor
p << x # so I push x into array#p
end
end
return p[-1] # returns the last element of the array, which is the largest
end
puts prime(99)
I'm not going to give you the full answer, as that would defeat the object of the practice with Project Euler.
However, you're almost on the right track with sorting out your problem. You don't want to look at the array p not being emptied, that should be collecting your primes. You do want to look at not_p though, since that is the array of divisors of each of your factors.
I hope this helps. Let me know if I can help any more.
Ah ok! Thanks for the suggestion philnash! In fact, I knew about that problem and tried to clear the array with Array.clear but that did not work. Instead, I just moved not_p = [] below the iteration arr.each do |x| and it worked! It makes sense because the not_p resets to [] when it moves on to the next element. Thanks so much for your help and for not providing the answer first! Here is my final, working solution =D
def prime(num)
arr = []
p = []
for i in (2..num / 2)
if num % i == 0
arr << i
end
end # this should output [3, 9, 11, 33]
arr.each do |x|
not_p = []
for i in (2..(x / 2))
if x % i == 0
not_p << i
end
end
if not_p.length == 0
p << x
end
end
return p[-1]
end
puts prime(99) # => 29

Largest prime factor in Ruby, without using require 'prime'

I'm trying to find the largest prime factor for a number x in Ruby, without using require 'prime'.
Here is the code
x=13195; n=2; max=n;
for n in (2...x)
if (x%n==0)
prime=true
for y in (1...n)
if n%y==0
prime=false
end
end
if prime
max=n
end
end
end
puts max
I know the code is loop-extensive. And it not very "Ruby-like'. I just need to understand the logical error in my code.
x is an array
x=13195, n=2, max=n # => x == [13195, 2, 2]
you need
x=13195; n=2; max=n;
so, it's obvious that (2...[13195, 2, 2]) is an invalid Range
require 'rubygems'
require 'prime'
x = 13195
#Solution suggested by steenslag
max = x.prime_divison.last.first
puts max # => 29

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)

Find second largest number from an array in Ruby

I have an array a = [3,6,774,24,56,2,64,56,34]. I need to find the second largest number in a single iteration using Ruby. How do I achieve it?
Simple:
array.sort[-2]
And you're done :)
This works, but am not sure for the "single iteration"
a.max(2)[1]
sort is probably overkill here, especially for really large arrays. Don't quite understand "single iteration", one line you mean?
a = [3,6,774,24,56,2,64,56,34]
b = a.shift(2).sort
c =
a.inject(b) do |(m2, m), e|
case
when e > m
[m, e]
when e > m2
[e, m]
else
[m2, m]
end
end
c.first #=> 64
Just for fun, this method gets the Nth greatest value in a enumerable (you'd use a bisect module to make the insertion into acc more efficient). As pointed out by #Victor, you would only use it when the length of the array is much bigger than n, othersize a simple array.sort[-n] is faster.
module Enumerable
def max_nth(n)
inject([]) do |acc, x|
(acc + [x]).sort[[acc.size-(n-1), 0].max..-1]
end.first
end
end
p [1, 5, 2, 32, 2, 41, 15, 55].max_nth(2) #=> 41
It works too:
arr.sort.reverse[1]
For me,
a = [3,6,774,24,56,2,64,56,34]
a.uniq # create a new array with the only unique value
a.sort[-2] # find the second greatest value
For me this worked:
data_array5 = [45,65632,232,34345,343,23,23,56]
puts data_array5.sort[data_array5.length()-2]
This is generic you replace 2 with any n number to get nth maxmium
array = [1,2,3,4,5,6]
puts array.max(2).last

Ruby simple way to list the next n numbers

In ruby we can easily generate 1 to n numbers by lots of ways, like
1.upto(10).to_a
[*1..10]
But I want to find out the next n numbers from the given number. For example, if the given number is 250, what's the simplest way to find the next 20 numbers (250..270)?
One way is:
n.upto(n+next),
So
250.upto(250+20) or [*250..(250+20)]
I just wanted to know if there is a default ruby method/way to handle this.
You can also make use of lazy evaluation on ranges, and do something like
250.upto(1.0/0).take(20)
I don't think there is something built-in in Ruby, but how to write your own method:
class Integer
def next_with_step(step = nil)
if step.is_a?(Fixnum)
upto(self + step).to_a
else
next_without_step
end
end
alias_method :next_without_step, :next
alias_method :next, :next_with_step
end
1.next
=> 2
1.next(3).inspect
=> [1, 2, 3, 4]
Here is an example of how you could accomplish this:
n = 250
m = 5
puts (0...m).map{ |i| i + n }.inspect #=> [250, 251, 252, 253, 254]

Resources