숫자 1부터 시작해서 우측으로부터 시계방향으로 감아 5×5 행렬을 만들면 아래와 같이 됩니다.
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
여기서 대각선상의 숫자를 모두 더한 값은 101 입니다.
같은 방식으로 1001×1001 행렬을 만들었을 때, 대각선상의 숫자를 더하면 얼마가 됩니까?
대각의 위치를 찾는 문제일까..
저런 행렬을 만드는 로직을 찾는 문제일까..
한참 고민하다가.. 각 4 모서리의 수에서 패턴발견..
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
sum=1 | |
rows=1002 | |
for n in range(3, 1002, 2): | |
up_r = n**2 | |
up_l = up_r - (n-1) | |
dn_l = up_l - (n-1) | |
dn_r = dn_l - (n-1) | |
print(up_r, up_l, dn_l, dn_r) | |
sum = sum + up_r + up_l + dn_l + dn_r | |
print(sum) |
Ruby
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
sum=1 | |
rows=1001 | |
(3..1001).step(2) do | |
|n| | |
up_r = n**2 | |
up_l = up_r - (n-1) | |
dn_l = up_l - (n-1) | |
dn_r = dn_l - (n-1) | |
puts "#{up_r}, #{up_l}, #{dn_l}, #{dn_r}" | |
sum = sum + up_r + up_l + dn_l + dn_r | |
end | |
puts sum |
Perl
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
use strict; | |
use warnings; | |
my $sum=1; | |
my $rows=1001; | |
foreach my $n ((3..1001)) { | |
if($n % 2 ==0) { | |
next; | |
} | |
my $up_r = $n * $n; | |
my $up_l = $up_r - ($n-1); | |
my $dn_l = $up_l - ($n-1); | |
my $dn_r = $dn_l - ($n-1); | |
print "$up_r, $up_l, $dn_l, $dn_r \n"; | |
$sum = $sum + $up_r + $up_l + $dn_l + $dn_r; | |
} | |
print $sum; |
perl도 python이나 ruby처럼 step을 줘서 돌릴 수 있는 방법이 있을 것도 같은데....흠