Skip to content

Instantly share code, notes, and snippets.

@kiyotune
Created August 20, 2012 08:37
Show Gist options
  • Save kiyotune/3402281 to your computer and use it in GitHub Desktop.
Save kiyotune/3402281 to your computer and use it in GitHub Desktop.
Project Euler 問題30
#!/usr/bin/perl
use strict;
use warnings;
my $pow = shift; # 5
my $max = calc_max($pow);
my $len = length($max); # 6
my $ans = 0;
for(my $i=2; $i<=$max; $i++)
{
my $aa = sprintf("%0".$len."s", $i);
my $v = 0;
#print $aa."\n"; next;
for(my $j=0; $j < $len; $j++){
my $a = substr($aa, $j, 1);
$v += $a**$pow;
}
if($v == $aa)
{
$ans += $v;
print "$aa\n";
}
}
print "Ans: $ans\n";
# f = a^n+b^n+c^n+d^n... が9999...より小さくなるfmaxを求める
sub calc_max
{
my $n = shift; # 5
my $fmax = 0;
my $aa = '';
for(my $i=1; ;$i++)
{
$aa .= 9;
$fmax += 9**$n;
if($fmax < $aa)
{
last;
}
}
return($fmax);
}
#004150
#004151
#054748
#092727
#093084
#194979
#Ans: 443839
@kiyotune
Copy link
Author

calc_maxのコメントを修正

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment