5
4

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 3 years have passed since last update.

Google recruit problem, exp and prime

Last updated at Posted at 2020-11-25

問題

  • {e(自然対数の底)の値で連続する 10 桁の数のうち,最初の素数} をを ruby で求めよ.ただし,e(自然対数の底)は 200 桁までである。

解法

  • 愚直な解法
    • e の値中の、連続する 10 桁の数
      • 数の読み込み
      • 10 桁の整数の生成
    • 素数判定
    • 最初の連続する 10 桁の素数を捜す

→ 計算時間が長く、工夫が必要

  • code
# coding: utf-8
def check_prime(n)

  (2...n).each do |q|
    if n % q == 0
      return 0
    else
      puts n,q
    end
  end

  return 1
end

e_num = String.new('2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274274663919320030599218174135966290435729003342952605956307381323286279434907632338298807531952510190')
i = 0
e_num = e_num.delete('.')
# 1.連続する 10 桁の数を読み込む
loop do
  num = e_num[i..i+9]
  if num.size() != 10 
    break
  else
    if check_prime(num.to_i) == 1
      puts num
      break
    else
      i += 1
    end
  end
end

参考

講義ページ

プロを目指す人のための Ruby 入門


  • source ~/classes/muli_scale/grad_members_20f/members/keita_k7/memo/l2.org
5
4
1

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
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?