素数 検索
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