6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby 色々な素数の求め方

Last updated at Posted at 2014-02-14

素数 検索

prime.rb
def prime_number(n)
  sqrt = Math.sqrt(n)
  factor_number = (2..sqrt).any? { |num| n % num == 0 }
  unless factor_number || n == 1
    "#{n}は素数です"
  else
    "#{n}は素数ではない"
  end
end

prime_number(1000)

##双子素数 検索

prime.rb

def twins_range_prime(numbers)
  prime_number = Proc.new { |number|
    sqrt = Math.sqrt(number)
    factor_number = (2..sqrt).any? { |num| number % num == 0 }
    unless factor_number || number == 1
      number
    end
    }
  array = []
  (1..numbers).each do |number|
    array << prime_number.call(number)
  end
  array.compact.each_cons(2).select{ |b, r| (r - b) == 2}
end

p twins_range_prime(1000)

##三つ子素数 検索

prime.rb

def prime_triplet(numbers)
   prime_number = lambda { |number|
    sqrt = Math.sqrt(number)
    factor_number = (2..sqrt).any? { |num| number % num == 0 }
    unless factor_number || number == 1
      number
    end
    }

  array = []
  (1..numbers).each do |number|
    array << prime_number.call(number)
  end
  array.compact.each_cons(3).select{ |a, b, c| (b - a == 2 && c - a == 6) || (b - a == 4 && c - a == 6) }
end

p prime_triplet(1000)

##四つ子素数 検索

prime.rb

def prime_quadruplet(numbers)
   prime_number = lambda { |number|
    sqrt = Math.sqrt(number)
    factor_number = (2..sqrt).any? { |num| number % num == 0 }
    unless factor_number || number == 1
      number
    end
    }

  array = []
  (1..numbers).each do |number|
    array << prime_number.call(number)
  end
  array.compact.each_cons(4).select{ |a, b, c, d| (b - a == 2 && c - a == 6 && d - a == 8) }
end

p prime_quadruplet(1000)

##メルセンヌ素数 検索

prime.rb

def mersenne_number(multiplier)
  prime_number = proc { |number|
    sqrt = Math.sqrt(number)
    factor_number = (2..sqrt).any? { |num| number % num == 0 }
    unless factor_number || number == 1
      "2の#{multiplier}乗は#{number}で素数です"
    else
      "2の#{multiplier}乗は#{number}で素数ではありません"
    end
  }

  number = (2 ** multiplier - 1)
  prime_number.call(number)
end

(1..10).each do |a|
puts mersenne_number(a)
end

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?