欧拉回文计划 #4 与 C

Project Euler Palindrome #4 with C

我发现很少有帖子使用 C 来解决这个问题。我的代码中的大部分元素都是独立工作的,但由于某种原因,开始的迭代导致了问题。首先,我收到 "exited with non-zero status" 错误消息。当我 运行 a 和 b 的范围较小的程序时,我没有收到该消息。我猜我创建的 rev_array 和 for_array 变量有问题。我确定我在这里做的事情真的很愚蠢,所以我提前为此道歉。

但是当我对 a 和 b 使用较小的范围(比如 10 到 25)时,程序仍然显示所有两位数(甚至 11、22、33、44)的正向和正向都不相同落后。我用 printf 来检查这个。

我制作了一个类似的程序,它使用 a 和 b 的固定值而不是迭代一系列值,并且运行良好。但我无法弄清楚为什么这个不起作用。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int max;
int a;
int b;
int prod;
int m = 0;
int rev_array[10000];
int for_array[10000];
int c;
int d;
int same = 0;

int main(void)
{
  // iterate over all 3 digit numbers in lines 19-21
  for(a = 10; a <= 25; a++)
  {
    for(b = 10; b <= 25; b++)
    {
      max = 0;
      prod = a * b;
      /* thanks to Zach Scrivena for the following formula converting an integer to an array of integers posted on Whosebug on February 5, 2009 under the subject "convert an integer number into an array"
      */
      int n = prod;
      while(n != 0)
      {
        rev_array[m] = n % 10;
        n /= 10;
        m++;
      }
      /* thanks to Jordan Lewis for the following int length formula posted to Whosebug on June 18, 2010 in response to "Finding the length of an integer in C"
      */
      int length = floor(log10(abs(prod))) + 1;
      // create the forward array of the ints in prod 
      for(c = length - 1, d = 0; c >= 0; c--, d++)
      {
        for_array[d] = rev_array[c];
      }
      // compare the forward and reverse arrays to see if they match exactly
      for(int e = 0; e < length; e++)
      {
        if(for_array[e] != rev_array[e])
        {
          // if they don't match then set same equal to 1 for following step
          same = 1;
        }
      }
      /* if prod is greater than max and the forward and reverse arrays are identical, then replace max with prod
      */
      if(prod > max && same == 0)
      {
        max = prod;
      }
      // reset same and repeat the process
      same = 0;
    }
  }
  // print the final, greatest number that fits the preceding criteria
  printf("new max: %i \n", max);
  return 0;
}

评论中提供的答案:

您每次都需要将m重置为零。 – 约翰尼莫普

您也不需要计算长度,因为 m 应该包含 while 循环后的长度(但您需要在顶部将其重置为 0)。并且所有这些变量都应该是局部的,并且它们中的大多数(如 m、n、prod)应该在内循环中定义,范围有限。 max 是唯一需要在迭代之间保留的值。 – 格鲁