Skip to content

Instantly share code, notes, and snippets.

@kiyotune
Created August 26, 2012 16:14
Show Gist options
  • Save kiyotune/3481371 to your computer and use it in GitHub Desktop.
Save kiyotune/3481371 to your computer and use it in GitHub Desktop.
Project Euler 問題35
#!/usr/bin/env perl
use strict;
use warnings;
use Math::Prime::XS qw(is_prime);
my %ans = ();
foreach my $no(2..999999)
{
#2桁以上の偶数の数字および5を含む数値は循環して一の位に来たときに素数ではなくなる為除外
($no>=10 && ($no=~/[024685]/)) and next;
#その数自身が素数の場合のみ続行
if(is_prime($no))
{
$ans{$no} = 1; #仮
#巡回数を取得
my @cyc_no = get_cyclic_no($no);
foreach my $cn (@cyc_no)
{
if(!is_prime($cn))
{
delete($ans{$no}); last;
}
}
}
}
print "Ans: ".(scalar keys %ans)."\n";
#
# 自分も含めた巡回数のリスト
#
sub get_cyclic_no
{
my $no = shift;
my @ret = ($no);
foreach(1..(length($no)-1))
{
$no =~ s/(\d*)(\d)$/$2$1/;
#例)121212 => 121212, 212121 の2通りのみとカウント
($no == $ret[0]) ? last : push(@ret, $no);
}
return (@ret);
}
#
# 素数かどうか(遅いので使わない)
#
#sub is_prime
#{
# my $no = shift;
#($no == 2) and return 1;
#for(my $div = 2; $div < $no; $div++)
#{
# (($no % $div) == 0) and return 0;
#}
#return 1;
#}
# Ans: 55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment