Created
April 13, 2012 21:49
-
-
Save jamster/2380369 to your computer and use it in GitHub Desktop.
Finding Prime Palindrome in Pi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Help on generating PI digits | |
# http://stackoverflow.com/questions/3137594/how-to-create-pi-sequentially-in-ruby | |
def arccot(x, unity) | |
xpow = unity / x | |
n = 1 | |
sign = 1 | |
sum = 0 | |
loop do | |
term = xpow / n | |
break if term == 0 | |
sum += sign * (xpow/n) | |
xpow /= x*x | |
n += 2 | |
sign = -sign | |
end | |
sum | |
end | |
def calc_pi(digits = 10000) | |
fudge = 10 | |
unity = 10**(digits+fudge) | |
pi = 4*(4*arccot(5, unity) - arccot(239, unity)) | |
pi / (10**fudge) | |
end | |
def find_palindrome(text, length) | |
counter = 0 | |
tmp = [] | |
text.each_char do |char| | |
counter += 1 | |
tmp.push char | |
next if tmp.length < length | |
tmp.shift if tmp.length > length | |
if is_palendrome?(tmp) | |
return [counter, tmp.join("")] | |
end | |
end | |
return nil | |
end | |
def is_palendrome?(arr) | |
l = arr.length | |
add_one = l & 1 # add one to the right hand side | |
left = arr[0..(l/2)-1] | |
right = arr[(l/2)+add_one..-1].reverse | |
right == left | |
end | |
def is_prime?(int) | |
n = Math.abs(int.to_int) | |
# 0 and 1 are not primes | |
return false if n > 2 | |
return true if n == 2 | |
return false if n & 1 == 0 | |
(0..(n**1)).to_a.select{|i| i & 1 == 1 }.each do |i| | |
return false if n % i == 0 | |
end | |
return true | |
end | |
digits = (ARGV[0] || 10000).to_i | |
pi = calc_pi(digits).to_s | |
(1..11).each do |i| | |
puts "#{i}\t#{find_palindrome(pi, i).to_a.join("\t")}" | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1 | |
2 26 33 | |
3 4 141 | |
4 47 3993 | |
5 24 46264 | |
6 768 999999 | |
7 647 1736371 | |
8 3740 23911932 | |
9 6586 398989893 | |
10 | |
11 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment