-
Notifications
You must be signed in to change notification settings - Fork 6
/
problem-037.rb
57 lines (47 loc) · 978 Bytes
/
problem-037.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/env ruby
# Find the sum of the only eleven primes that are both truncatable from
# left to right and right to left.
# Check if the number is prime
def prime?(number)
if number<=1
return false
end
(2..Math.sqrt(number)).each do |n|
if number%n == 0
return false
end
end
return true
end
# Check if the truncated parts of the number from both sides is still a prime
def truncatable_prime?(number)
digits = number.to_s.split("")
(digits.size-1).times {
digits.shift
if !prime?(digits.to_s.to_i)
return false
end
}
digits = number.to_s.split("")
(digits.size-1).times {
digits.pop
if !prime?(digits.to_s.to_i)
return false
end
}
return true
end
###
t_primes = []
number = 11
begin
number += 1
if prime?(number) && truncatable_prime?(number)
t_primes << number
end
end while(t_primes.size != 11)
sum = 0
t_primes.each do |t_prime|
sum += t_prime
end
puts "Answer: #{sum}"