Ruby/Number/Prime Numbers

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

Generates 25 prime numbers from 2 to 97

require "mathn"
list_primes = Prime.new
puts list_primes.each { |prime| print prime, " "; break unless prime < 90 }



Generating Prime Numbers with succ

require "mathn"
primes = Prime.new
primes.succ                                     # => 2
primes.succ                                     # => 3



Pass code block into each

require "mathn"
primes = Prime.new
primes.each { |x| puts x; break if x > 15; }
# 5
# 7
# 11
# 13
# 17
primes.succ                                     # => 19



Prime Numbers

require "mathn"
prime_number = Prime.new # instantiate a Prime object
prime_number.next # => 2 # return the next prime number (seed = 1)
prime_number.succ # => 3 # succ works, too
# print the next prime number as a string
puts "The next prime number is " + prime_number.next.to_s + "."



Use each method from Prime class

#!/usr/bin/env ruby
require "mathn"
list_primes = Prime.new
list_primes.each { |prime| print prime, " "; break unless prime < 90 }



Use Prime to generate prime numbers

#!/usr/bin/env ruby
require "mathn"
prime_number = Prime.new # instantiate a Prime object
prime_number.next # => 2 # return the next prime number (seed = 1)
prime_number.succ # => succ works, too
# print the next prime number as a string
puts "The next prime number is " + prime_number.next.to_s + "."
# => The next prime number is 5.