Palindrome来自两个3位数字的乘积

时间:2011-09-18 09:13:30

标签: python palindrome

我想找到通过两个3位数字相乘得到的最大回文数据。

我开始时a和b均为999,并且每发生一次乘法就减少a和b。

a = 999 #Defining Variables
b = 999

for i in range (1000): 
    c= a*b                          #multiply a to b
    if int(str(c)[::-1]) == c:
        print c
    a = a-1                         #decrement the value of a
    c=a*b                           #multiply a by the decremented a
    if int(str(c)[::-1]) == c:
        print c

    b = b-1                         #decrement b so that both a and b have been decremented

结果出现了698896,289982,94249,69696 ...... 698896是第一个数字。目前我还在试图找出我所缺少的东西。

6 个答案:

答案 0 :(得分:14)

你不能以交替方式递减ab,因为你错过了a = 999和b = 997这样的价值对。

尝试嵌套循环,从999开始并向后计数。

这样的东西
def is_pal(c):
    return int(str(c)[::-1]) == c

maxpal = 0
for a in range(999, 99, -1):
    for b in range(a, 99, -1):
        prod = a * b
        if is_pal(prod) and prod > maxpal:
            maxpal = prod

print maxpal

编辑:在保罗的评论之后修改了下限。

答案 1 :(得分:3)

你算法错了。您将需要测试a的所有值的所有值,这可以通过使用两个循环来解决(外部用于a,内部用于b)。我还建议您使用a和b作为循环索引,这简化了逻辑(使其更容易保持在头部)。

考虑将回文检查移动到它自己的功能,以使代码更容易理解。


我不是Python程序员,但这是我在PHP中的解决方案:

function palindrome($x) {
  $x = (string) $x;  //Cast $x to string
  $len = strlen($x); //Length of $x

  //Different splitting depending on even or odd length
  if($len % 2 == 0) {
    list($pre, $suf) = str_split($x, $len/2);
  }else{
    $pre = substr($x, 0, $len/2);
    $suf = substr($x, $len/2+1);
  }

  return $pre == strrev($suf);
}

$max = array(0, 0, 0);

//Loop $a from 999 to 100, inclusive.
//Do the same over $b for EVERY $a
for($a = 999; $a >= 100; $a--) {
  for($b = 999; $b >= 100; $b--) {
    $x = $a*$b;

    if(palindrome($x)) {
      echo $a, '*', $b, ' = ', $x, "\n";
      if($x > $max[2]) {
        $max = array($a, $b, $x);
      }
    }
  }
}
echo "\nLargest result: ", $max[0], '*', $max[1], ' = ', $max[2];

答案 2 :(得分:1)

最快的方法是在最大值999x999 = 998001之前从最大的polindrome下降。 997799,996699,..并检查每个是否可分为A和B,范围为100..999。我的代码花了2200个周期。您的代码大约需要4K到8K周期。

Sub method3a()
iterations = 0
For a = 997 To 0 Step -1
    R = a * 1000 + Val(StrReverse(a))
    b = 999      ' R=b*s
    s = Int(R / b)
    While b >= s
        iterations = iterations + 1
        If R = b * s Then
            Debug.Print "Result=" & R & " iterations=" & iterations
            Exit Sub
        End If
        b = b - 1
        s = Int(R / b)
    Wend
Next

End Sub

答案 3 :(得分:1)

i = 1000000
test = 0
while test == 0:
    i += -1
    str_i = str(i)
    if str_i[0:3] == str_i[3:][::-1]:
        for j in range(100, 1000):
            if i % j == 0:
                if i/j < 1000 and i/j > 100:
                    print('Largest Palindrome: %s = %s * %s' % (i, j, i//j))
                    test = 1
                    break

答案 4 :(得分:0)

在C#中 - 在gist中解决 - https://gist.github.com/4496303

公共班级工作人员     {         公共工作者(){

    }
    public void start()
    {
        int MAX_NUMBER = 999;
        for (int Number = MAX_NUMBER; Number >= 0; Number--)
        {
            string SNumberLeft = Number.ToString();
            string SNumberRight = Reverse(Number.ToString());
            int palindromic = Convert.ToInt32(SNumberLeft + SNumberRight);

            for (int i = MAX_NUMBER; i >= 1; i--)
            {
                for (int l = MAX_NUMBER; l >= 1; l--)
                {
                    if ((i * l) - palindromic == 0)
                    {
                        System.Diagnostics.Debug.WriteLine("Result :" + palindromic);
                        return;
                    }
                }
            }

           // System.Diagnostics.Debug.WriteLine( palindromic); 
        }           

    }

    public string Reverse(String s)
    {
        char[] arr = s.ToCharArray();
        Array.Reverse(arr);
        return new string(arr);
    }



}

答案 5 :(得分:0)

我做到了并优化并减少了搜索步骤的数量

时间0.03525909700010743

回文数= 906609

count = 3748

i = 913

j = 993

from timeit import timeit

def palindrome(number):
    return str(number) == str(number)[::-1] # chek number is polindrome

def largest():
    max_num = 0
    count = 0
    ccount = 0
    ii = 0
    jj = 0
    for i in range(999, 99, -1): # from largest to smallest
        for j in range(999,  i - 1, -1): # exclude implementation j * i
            mult = i * j # multiplication
            count += 1
            if mult > max_num and palindrome(mult): # chek conditions
                max_num = mult #remember largest
                ii = i
                jj = j
                ccount = count
    return "\npalindrome = {0}\ncount = {1}\ni = {2}\nj = {3}".format(max_num, ccount, ii, jj)
print ("time", timeit('largest()', 'from __main__ import largest', number = 1))
print(largest())