본문 바로가기

오일러프로젝트

[오일러프로젝트] 38번문제


숫자 192에 1, 2, 3을 각각 곱합니다.

192 × 1 = 192
192 × 2 = 384
192 × 3 = 576

곱한 결과를 모두 이어보면 192384576 이고, 이것은 1 ~ 9 팬디지털(pandigital)인 숫자입니다. 이런 과정을 편의상 '곱해서 이어붙이기'라고 부르기로 합니다.

같은 식으로 9와 (1, 2, 3, 4, 5)를 곱해서 이어붙이면 918273645 라는 1 ~ 9 팬디지털 숫자를 얻습니다.

어떤 정수와 (1, 2, ... , n)을 곱해서 이어붙였을 때 얻을 수 있는 가장 큰 아홉자리의 1 ~ 9 팬디지털 숫자는 무엇입니까? (단 n > 1)

일단...
맨 앞자리는 9로 시작해야 가장 클 것이라서 (예로 918273654가 나왔기 때문에 최소한 이거보다 크거나 같겠지..) 맨 처음 n은 1이 됨..

n이 3까지 가게 되면 자리 수를 넘는다.

pandigital 중 가장 큰 수는 987654321이고...

9 * (1,2) = 918
98 * (1,2) = 98916
..
9876 * (1,2) = 987619752

이 이상은 자리수가 9를 넘게 된다.

대략 탐색범위를 9000 ~ 9876으로 잡으면 될 듯 함...대략..;;;;

 


Python
def isPandigital(n):
if (len(n) == 9):
temp_l = ''.join(sorted([ c for c in n]))
if temp_l == '123456789':
return True;
return False
result = 0
for n in range(9183, 9877):
a1 = str(n * 1) + str(n * 2)
if isPandigital(a1):
if result < int(a1):
result = int(a1)
print (result)
view raw 38.py hosted with ❤ by GitHub

Ruby
def isPandigital(n)
temp_array = Array.new
if n.length == 9
n.each_char { |c| temp_array.push(c) }
temp_array.sort!
temp_s = temp_array.join
if temp_s == "123456789"
return true
end
end
return false
end
result = 0
(9183..9877).each do |n|
a1 = (n * 1).to_s + (n * 2).to_s
if isPandigital(a1)
if result < a1.to_i
result = a1.to_i
end
end
end
puts result
view raw 38.rb hosted with ❤ by GitHub

Perl
sub isPandigital {
my ($n) = @_;
if (length $n == 9) {
my @temp_l = split //, $n;
@temp_l = sort @temp_l;
my $temp_s = join("", @temp_l);
if ($temp_s =~ m/123456789/) {
return 1;
}
}
return 0;
}
my $result = 0;
foreach my $n ((9183..9877)) {
my $a1 = ($n*1).($n*2);
if (isPandigital($a1)) {
if ($result < $a1) {
$result = $a1;
}
}
}
print "$result";
view raw 38.pl hosted with ❤ by GitHub