欧拉计划问题 4

kac*_*ous 0 c

我已经为 Project Euler 上的问题 4 创建了一个解决方案。但是,我发现将打印语句(打印答案)放在不同位置会打印不同的答案。不知什么原因,结果的最高值是580085。不应该是906609吗?我的 isPalindrome() 方法有问题吗?

 #include <stdio.h>
 #include <stdbool.h>

 int isPalindrome(int n);

 //Find the largest palindrome made from the product of two 3-digit numbers.
 int main(void)
 {    
      int i = 0;
      int j = 0;
      int result = 0;
      int palindrome = 0;
      int max = 0;

      //Each iteration of i will be multiplied from j:10-99
      for(i = 100; i <= 999; i++)
      {
            for(j = 100; j <= 999; j++)
            {
                  result = i * j; 
                  if(isPalindrome(result) == 0)
                  {
                       //printf("Largest Palindrome: %d\n", max); //906609
                       //printf("Result: %d\n", result); //580085
                       if(result > max)
                       {
                            max = result;
                            //printf("Largest Palindrome: %d\n", max); //927340
                       }      
                       printf("Largest Palindrome: %d\n", max); //906609
                  }
            }
       } 

       //printf("Largest Palindrome: %d\n", max); //998001

      system("PAUSE");
      return 0;
 } //End of main

 //Determines if number is a palindrome
 int isPalindrome(int num)
 {
      int n = num;
      int i = 0;
      int j = 0;
      int k = 0;
      int count = 0;
      int yes = 0;

      //Determines the size of numArray
      while(n/10 != 0)
      {
           n%10;
           count++;
           n = n/10;
      }

      int numArray[count];

      //Fill numArray with each digit of num
      for(i = 0; i <= count; i++)
      { 
           numArray[i] = num%10;
           //printf("%d\n", numArray[i]);  
           num = num/10;
      }

      //Determines if num is a Palindrome     
      while(numArray[k] == numArray[count])
     {
           k = k + 1;
           count = count - 1;  
           yes++;
      }

      if(yes >= 3)
     {
           return 0; 
      }

}//End of Function
Run Code Online (Sandbox Code Playgroud)

Vin*_*ura 5

我记得不久前做过这个问题,我只是做了一个is_palindrome()函数并对其进行了暴力破解。我从 999*999 向下开始测试。

我检测回文的方法与您的完全不同。我会将给定的数字转换为字符串,并将第一个字符与第 n 个字符进行比较,将第二个字符与 n-1 进行比较,依此类推。

这很简单(也可能效率低下),但答案会“立即”出现。