-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlargestPalindrome.py
61 lines (53 loc) · 2.11 KB
/
largestPalindrome.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
'''
Largest palindrome product
https://projecteuler.net/problem=4
'''
def reverse(n):
r = 0
while n>0:
r = 10*r + n%10 # Awesome
n //=10
return r
def isPalindrome(n):
return n == reverse(n)
largestPalindrome = 0
a = 999
while a>=100:
if a%11 == 0:
b = 999
db = 1
else:
b = 990
db = 11
while b>=a:
if a*b <= largestPalindrome:
break
if isPalindrome(a*b):
largestPalindrome = a*b
b -= db
a -= 1
print(largestPalindrome)
'''My solution'''
p = [869968, 870078, 871178, 872278, 873378, 874478, 875578, 876678, 877778, 878878, 879978,
880088, 881188, 882288, 883388, 884488, 885588, 886688, 887788, 888888, 889988, 890098,
891198, 892298, 893398, 894498, 895598, 896698, 897798, 898898, 899998, 900009, 901109,
902209, 903309, 904409, 905509, 906609, 907709, 908809, 909909, 910019, 911119, 912219,
913319, 914419, 915519, 916619, 917719, 918819, 919919, 920029, 921129, 922229, 923329,
924429, 925529, 926629, 927729, 928829, 929929, 930039, 931139, 932239, 933339, 934439,
935539, 936639, 937739, 938839, 939939, 940049, 941149, 942249, 943349, 944449, 945549,
946649, 947749, 948849, 949949, 950059, 951159, 952259, 953359, 954459, 955559, 956659,
957759, 958859, 959959, 960069, 961169, 962269, 963369, 964469, 965569, 966669, 967769,
968869, 969969, 970079, 971179, 972279, 973379, 974479, 975579, 976679, 977779, 978879,
979979, 980089, 981189, 982289, 983389, 984489, 985589, 986689, 987789, 988889, 989989,
990099, 991199, 992299, 993399, 994499, 995599, 996699, 997799, 998899, 999999][::-1]
for x in p:
for d in range(999,99,-1):
# print('current', x, x/d, d, sep='\t')
if x%d==0 and (x//d > 99 and x//d < 1000):
print('Largest palindrome product', x, x//d, d, sep='\t')
break
elif x/d > 999:
# print('> 999', x, x/d, d, sep='\t')
break
# oneline solution from forum
max([x*y for x in range(900,1000) for y in range(900,1000) if str(x*y) == str(x*y)[::-1]])