[RUBY] Google Recruit

Introduction

This time, we will implement the code to solve "Google Recruit" and "Similar subject (final task)" in the following articles in Ruby.

Google Recruit

Output the first prime number of 10 consecutive digits with the value of $ e $ (base of natural logarithm). However, $ e $ is the following number.

2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274274663919320030599218174135966290435729003342952605956307381323286279434907632338298807531952510190

input

First, read the above $ e $ value from the standard input.

google_recruit.rb


exp = gets.to_s.chomp
exp = exp[0] + exp[2...exp.length]

Primality test

Next, we implement the function is \ _prime that determines whether the given natural number $ n $ is a prime number. For natural numbers $ a, b $ such that $ a \ times b = n $, if $ \ sqrt {n} <a $, then $ b <\ sqrt {n} $ holds, so from 2 to $ \ sqrt {n} $ You can judge whether $ n $ is a prime number by trying whether $ n $ is divisible by the natural numbers up to. The amount of calculation is $ O (\ sqrt {n}) $.

google_recruit.rb


def is_prime(n)
  for i in 2..n do
    if n < i*i
      break
    end
    if n % i == 0
      return false
    end
  end

  return n != 1
end

Output the answer

The answer to the problem is output by cutting out 10 consecutive digits from the character string and making a primality test.

google_recruit.rb


for i in 0...exp.length - 10 do
  if exp[i] == '0'
    next
  end
  n = exp[i...i+10].to_i
  if is_prime(n)
    puts n
    break
  end
end

answer

As a result of executing the above program, the answer was 7427466391.

Similar subject (final task)

Find the following f (5).

f(1)=7182818284
f(2)=8182845904
f(3)=8747135266
f(4)=7427466391
f(5)=__________

Consideration

The 10 digits included in the $ e $ given earlier, whose sum of numbers is 49, are f (1), f (2), & # x2026; in order from the front (the problem is google as it is). You can find out (by doing a search). Therefore, write a program that finds such a 10-digit number that appears fifth.

program

10 consecutive digits are cut out from the character string, it is judged whether the sum of numbers is 49, and the 5th digit from the front is output.

google_recruit_final.rb


exp = gets.to_s.chomp
exp = exp[0] + exp[2...exp.length]

cnt = 0
for i in 0...exp.length - 10 do
  digit_sum = 0
  for j in 0...10 do
    digit_sum += exp[i + j].to_i
  end

  if digit_sum == 49
    cnt += 1
  end

  if cnt == 5
    puts exp[i...i+10]
    break
  end
end

answer

As a result of executing the above program, the answer was 5966290435.


Recommended Posts

google recruit
google recruit
google recruit
google recruit
Google Recruit
Google Recruit
Google Recruit
Google Recruit
Google recruit problem
EX2: Google Recruit
Google recruit problem, exp and prime
google java format