ruby中对质数的操作

def prime(n)
  return [] if n < 2
  return [2] if n == 2
  result = [2]
  3.upto(n) do |i|
    r = result.dup
    r.each_with_index do |ele,index|
      break if i.gcd(ele) != 1
      result << i if i.gcd(ele) == 1 && index == r.size - 1
    end
  end
  result
end

上面的方法是返回一个数组(给出一个n,然后返回n以内的所有质数)

然后如果想简单的话。。。。用下面的

require 'prime'

def prime(n)
  Prime.take_while { |p| p <= n }
end

Prime的方法如下:

Prime.methods
[:instance, :method_added, :each, :prime?, :int_from_prime_division, :prime_division, :to_a, :entries, :sort, :sort_by, :grep, :count, :find, :detect, :find_index, :find_all, :select, :reject, :collect, :map, :flat_map, :collect_concat, :inject, :reduce, :partition, :group_by, :first, :all?, :any?, :one?, :none?, :min, :max, :minmax, :min_by, :max_by, :minmax_by, :member?, :include?, :each_with_index, :reverse_each, :each_entry, :each_slice, :each_cons, :each_with_object, :zip, :take, :take_while, :drop, :drop_while, :cycle, :chunk, :slice_before, :lazy, :allocate, :new, :superclass, :freeze, :===, :==, :<=>, :<, :<=, :>, :>=, :to_s, :inspect, :included_modules, :name, :ancestors, :instance_methods, :public_instance_methods, :protected_instance_methods, :private_instance_methods, :constants, :const_get, :const_set, :const_defined?, :const_missing, :class_variables, :remove_class_variable, :class_variable_get, :class_variable_set, :class_variable_defined?, :public_constant, :private_constant, :module_exec, :class_exec, :module_eval, :class_eval, :method_defined?, :public_method_defined?, :private_method_defined?, :protected_method_defined?, :public_class_method, :private_class_method, :autoload, :autoload?, :instance_method, :public_instance_method, :nil?, :=~, :!~, :eql?, :hash, :class, :singleton_class, :clone, :dup, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :frozen?, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variables, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send, :respond_to?, :extend, :display, :method, :public_method, :define_singleton_method, :object_id, :to_enum, :enum_for, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__, :__id__]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 第5章 引用类型(返回首页) 本章内容 使用对象 创建并操作数组 理解基本的JavaScript类型 使用基本类型...
    大学一百阅读 8,466评论 0 4
  • Ruby 数组(Array) Ruby 数组是任何对象的有序整数索引集合。数组中的每个元素都与一个索引相关,并可通...
    黑夜的眸阅读 4,766评论 0 0
  • 1 了不起的匠人明华堂堂主。 汉服在今天又有什么价值呢?民族服饰在今天不同的民族和国家中,它最主要的用途就是文化礼...
    林风起阅读 3,355评论 0 4
  • 001 首先,并不是每个人都适合结婚。 如果人生如戏,结不结婚这件事,要看你是普通玩家,还是高级玩家。普通玩家选择...
    卓子云阅读 2,415评论 0 1
  • 最近在阅读《反脆弱》这本书,和大家分享下。 这本书的作者塔勒布也是畅销书《黑天鹅》的作者,在这本书中作者围绕不确定...
    香9醋阅读 3,870评论 0 0