4
0

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

Last updated at Posted at 2020-11-26

!Mac OS X-10.15.7 !ruby-2.7.1p83

Google Recruit

講義ページリンク

Google recruit problem, exp and prime

課題

ネイピア数(200桁)に出現する10桁の整数のうち一番初めに登場する素数を求める

方法

  • 先頭から順番に10文字ずつ切り取って素数判定する

解答例

"google_recruit.rb"
#!/usr/bin/env ruby
# frozen_string_literal: true

napier = File.read('napier.txt').delete('.')
digit_num = 10

def prime?(n)
  false if n == 1
  2.upto(Math.sqrt(n).to_i) do |i|
    return false if (n % i).zero?
  end
  true
end

(0..napier.length - digit_num).each do |i|
  n = napier.slice(i, digit_num).to_i
  if prime?(n)
    puts n
    break
  end
end
"napier.txt"
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274274663919320030599218174135966290435729003342952605956307381323286279434907632338298807531952510190

出力

> ruby google_recruit.rb
7427466391

NOTE

  • prime?は(この問題では心配ないが)1はfalseになることを忘れないようにする
    • 中身はほとんど講義ページと同じ
  • 配列のスライスは .slice(pos, size) でposから長さsizeで切り出す事ができる

  • source ~/multiscalesim_toku/grad_members_20f/members/lynd2299/google_recruit.org
4
0
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
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?