我正在解决项目Euler question 58。这里通过以1开始并以下列方式逆时针旋转来创建一个正方形(这里的边长等于7:
37 36 35 34 33 32 31
38 17 16 15 14 13 30
39 18 5 4 3 12 29
40 19 6 1 2 11 28
41 20 7 8 9 10 27
42 21 22 23 24 25 26
43 44 45 46 47 48 49
问题是当我们在对角线上的素数与对角线中的数量之比小于0.10时,我们一直在绕着正方形旋转。
我确信我有以下代码的解决方案(请参阅代码注释以获得澄清),但该网站指出我输入时答案是错误的。
require 'prime'
# We use a mathematical derivation of the corner values, keep increasing the value till we find a ratio smaller
# than 0.10 and increase the grid_size and amount of numbers on diagonals each iteration
side_length = 3 # start with grid size of 3x3 so that we do not get into trouble with 1x1 grid
prime_count = 3 # 3, 5, 7 are prime and on a diagonal in a 3x3 grid
diagonal_size = 5
prime_ratio = 1 # dummy value bigger than 0.10 so we can start the loop
while prime_ratio >= 0.10
# Add one to prime count for each corner if it is prime
# Corners are given by n2 (top left), n2-n+1, n2-2n+2, and n2-3n+3
prime_count += 1 if (side_length**2).prime?
prime_count += 1 if (side_length**2-side_length+1).prime?
prime_count += 1 if (side_length**2-2*side_length+2).prime?
prime_count += 1 if (side_length**2-3*side_length+3).prime?
# Divide amount of primes counted by the diagonal length to get prime ratio
prime_ratio = prime_count/diagonal_size.to_f
# Increase the side length by two (full spiral) and diagonal size by four
side_length += 2 and diagonal_size += 4
end
puts side_length-2 #-2 to account for last addition in while-loop
# => 26612
可能是错的,网站是对的。我现在坚持这个问题很长一段时间了。谁能指出我的错误?
答案 0 :(得分:3)
side_length += 2 and diagonal_size += 4
应该在循环的开头。
无法检查,我没有安装ruby,但我可以在我的python解决方案上重现同样的问题。