[RUBY] google recruit

!Mac OS X-10.15.7!ruby-2.7.1p83

Task

Find the first prime number of 10 consecutive digits of e (base of natural logarithm) with ruby. (However, e (base of natural logarithm) is limited to 200 digits)

2.71828182845904523536028747135266249775
7247093699959574966967627724076630353547
5945713821785251664274274663919320030599
2181741359662904357290033429526059563073
81323286279434907632338298807531952510190

First, let's roughly divide the program. 1. 1. Read data from text. 2. 2. Primality test. 3. 3. Extracts consecutive 10-digit numbers, main function

-1. Read data from text

def getdata()
      tmps=readlines.map(&:chomp)
      tmp=tmps.join
      e=tmp.delete('.')
      return e
end

The map method repeatedly executes blocks for the number of elements. The return value is returned as an array. Performs the process of deleting line breaks with chomp. After that, after converting to a character string, the decimal point is deleted.

-2. Primality test.

def judge(n)
      return false if n%2==0
      for i in 3...Math.sqrt(n) do
	  return false if n%i==0
	  i+=2
      end
      return true
end

First, as a major premise, even numbers are deleted, and 2 is not considered this time. The following properties are used for odd numbers of 3 or more. "Composite number x has a prime factor p that satisfies p ≤ √ x" That is, "composite number x has a prime factor p that satisfies p ≤ √ x" = "If x is a composite number, a divisor less than or equal to √x Find something that does not meet the conditions described in "Having a number".

-3. Extract consecutive 10-digit numbers, main function

def main
      data=getdata()
      while data.length>=10 do
	    n=data.slice(0, 10)
	    break if judge(n.to_i) 
	    data.slice!(0)
      end
      puts "A.#{n}"
end

Receives the base of the 200-digit natural logarithm, receives consecutive 10-digit numbers, and judges.

When executed,

$ ruby google.rb < e.txt
A.7427466391

\ * Reference-Primality test


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