Keep Hacking :)

Life is complex, it has both real and imaginary parts.

Project Euler 206的解答

其實是單純覺得這題蠻簡單的,而且一下就寫完了,所以就順手把它寫一下。

題目是要找出一個唯一的正整數,使得它的平方長得要像1_2_3_4_5_6_7_8_9_0這種形式。因爲數字是平方數,不難判斷最後是00結尾,所以要判斷的地方就更少了一點。解决的方法是直接採用暴力法,從上界往回找,直到符合這個形式。

程式碼:

1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/env ruby

upper_bound = 19_293_949_596_979_899
upper_bound_sqrt = (Math.sqrt(upper_bound) + 1).to_i

while true
  break if (upper_bound_sqrt**2).to_s.match(/1.2.3.4.5.6.7.8.9/)
  upper_bound_sqrt -= 2
end

puts upper_bound_sqrt * 10

本來還想對做平方的數字做最佳化,其實奇數也只有3跟9的平方尾數會是9,但是没有最佳化的程式就跑得夠快了,所以就懶得最佳化了:p

Comments