[四年前的博客,有一陣用perl刷projecteuler,呵呵,可惜很多都是數論的問題,好好好怕怕]
#Question 360
use Time::HiRes qw(gettimeofday) ;
my ($start_sec, $start_usec) = gettimeofday() ;
# 2**10 * 5**10 == 10**10
my $r = 3125;
my $e = 0.00001;
my $r2 = $r*$r;
#initial, (0, 0, r) and (0, 0, -r)
my $total = $r*2;
for my $z ( 0 .. ($r-1) ){
#at x-y plane, find d
my $d2 = ($r2) - ($z*$z);
my $d = sqrt( $d2 );
#iterate y
for my $y( 1 .. ($d) ){
my $x = sqrt( $d2 - ($y*$y) );
#next unless ( int($x) == $x );
next unless( abs(int($x) -$x) <= $e );
#print "($x, $y, $z)\n";
if( $z==0 ){
$total += ($x + $y + $z) * 4;
}
else{
$total += ($x + $y + $z) * 8;
}
}
}
print "Result is :" . $total . "\n";
my ($end_sec, $end_usec) = gettimeofday() ;
Given two points (x1,y1,z1) and (x2,y2,z2) in three dimensional space, the Manhattan distance between those points is defined as
|x1-x2|+|y1-y2|+|z1-z2|.
Let C(r) be a sphere with radius r and center in the origin O(0,0,0).
Let I(r) be the set of all points with integer coordinates on the surface of C(r).
Let S(r) be the sum of the Manhattan distances of all elements of I(r) to the origin O.
E.g. S(45)=34518.
Find S(1010).