Road to Data Analyst/Python

[Project Euler] Q4 : Largest palindrome product

kimbop 2022. 6. 4. 08:51

Q4 : A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.

 

문제 : 세자리 숫자를 곱하여 나오는 대칭수 중 최댓값을 찾아야 함.

 

(1) 최소 다섯자리 (100 * 100 = 10,000) 부터 여섯자리 (999 * 999 = 998,001) 중에서 대칭수를 찾고

(2) 그 중 최댓값을 구해야 함

 

(1) 최소 다섯자리 (100 * 100 = 10,000) 부터 여섯자리 (999 * 999 = 998,001) 중에서 대칭수를 찾고

- 100부터 999까지 증가하는 반복문 두개 필요

- 반복문에 증가하는 수에 맞추어 두 수의 곱셈.

- 다섯자리인지 여섯자리인지 알기 위해 len() 사용

- 곱셈 결과의 자리수에 맞추어 대칭하는지 == 로 확인

- 대칭한다면, 그 결과값을 int값으로 변환, result 배열에 추가

(개념 참고 : https://eclipse360.tistory.com/20 )

 

(2) 그 중 최댓값을 구해야 함

- max를 활용하여 최댓값 출력

 

코드

product = 0
result = []

for first in range(100, 999):
    for second in range(100, 999):
        product = str(first * second)
        if len(product) == 6:
            a, b, c, d, e, f = product[0], product[1], product[2], product[3], product[4], product[5]
            if a == f and b == e and c == d:
                result.append(int(product))
        else:
            a,b,c,d,e = product[0], product[1], product[2], product[3], product[4]
            if a == e and b == d:
                result.append(int(product))
print(max(result))