Created
August 20, 2012 03:57
-
-
Save kiyotune/3400540 to your computer and use it in GitHub Desktop.
Project Euler 問題29
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
#!/usr/bin/perl | |
use strict; | |
use warnings; | |
use Math::BigInt; | |
my ($amin, $amax, $bmin, $bmax) = @ARGV; # 2 100 2 100 | |
my $len = length((Math::BigInt->new($amax)**$bmax)->as_hex()) - 2; | |
my %arr; | |
my $v; | |
for(my $i=$amin; $i<=$amax; $i++) | |
{ | |
for(my $j=$bmin; $j<=$bmax; $j++) | |
{ | |
$v = (Math::BigInt->new($i) ** $j)->as_hex(); #prefix '0x' | |
$v = substr($v, 2); | |
$v = sprintf("%0".$len."s", $v); | |
#print "$v\n"; | |
$arr{$v} = 1; | |
} | |
} | |
my @arr = sort {$a cmp $b} keys %arr; | |
print "($amin<=a<=$amax, $bmin<=b<=$bmax) Ans: ".(scalar @arr)."\n"; | |
#(2<=a<=100, 2<=b<=100) Ans: 9183 |
32bit OS だと use bigint はダメなのね...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
毎回 Math::BigInt のインスタンスを生成しているので遅い。
BigInt->new() に $i*$j と直接累乗の計算を入れてしまうと、$i$jの計算結果(普通のint型(32bit/64bit))がnewに渡されるので意味ない。
BigInt->new($i) ** $j という風にしなければだめ。
ソートは答えそのものには関係ないが参考までに(hex文字列を0埋めして文字列として比較)。