LoginSignup
5
1

More than 3 years have passed since last update.

Google recruit problem (exp and prime)

Last updated at Posted at 2020-11-19

概要

ネイピア数 e の連続する 10 桁の数のうち、最初の素数を Ruby で求める

ただし、e は 200 桁まででよい

2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274274663919320030599218174135966290435729003342952605956307381323286279434907632338298807531952510190

ref:

(Ruby 勉強中)

コード

 1  def is_prime(num)
 2    warden = true
 3    for i in Range.new(2, Math::sqrt(num - 1))
 4      if num % i == 0
 5        warden = false
 6        break
 7      end
 8    end
 9    return warden
10  end
11  
12  exp = gets.chomp
13  exp = exp.delete('.')
14  
15  for i in Range.new(0, exp.length - 10)
16    ten_digits = exp.slice(i .. i + 9).to_i
17    if is_prime(ten_digits)
18      puts ten_digits
19      break
20    end
21  end

line1~10:

  • 素数かどうかを判定する method を作成する

ine12~13:

  • 以下のテキストファイルを読み込む

ファイル:

2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274274663919320030599218174135966290435729003342952605956307381323286279434907632338298807531952510190
  • 小数点を取り除く

line15~21:

  • ループを回して、前から順に連続する10桁の数字が素数かどうかを判定する
  • 素数が見つかれば終了し、見つかった素数を出力する

結果は以下の通り

7427466391

  • source ~/doc/lecture/multi-scale/grad_members_20f/members/yukiue/docs/google_recruit.org
5
1
3

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
1