开发者

Project Euler Problem 4

开发者 https://www.devze.com 2023-03-26 20:44 出处:网络
I\'ve created a solution to problem 4 on Project Euler. However, what I find is that placing the print statement (that prints the answer) in different locations prints different answers. And for some

I've created a solution to problem 4 on Project Euler. However, what I find is that placing the print statement (that prints the answer) in different locations prints different answers. And for some reason, the highest value of result is 580085. Shouldn't it be 906609? Is there something wrong with my isPalindrome() method?

 #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开发者_如何学JAVA 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


I remember doing that problem a while ago and I simply made a is_palindrome() function and brute-forced it. I started testing from 999*999 downwards.

My approach to detect a palindrome was rather different from yours. I would convert the given number to a string and compare the first char with the nth char, second with n-1 and so on.

It was quite simple (and might be inefficient too) but the answer would come up "instantly".


There is no problem in the code in finding the number.
According to your code fragment:

.
.
       }      
                       printf("Largest Palindrome: %d\n", max); //906609
                  }
            }
       } 

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

      system("PAUSE");
.
.
.

you get the result as soon as a palindrome number is found multiplying the number downwards.

You should store the palindrome in a variable max and let the code run further as there is a possibility of finding a greater palindrome further.

Note that for i=800,j=500, then i*j will be greater when compare with i=999,j=100. Just understand the logic here.


A few issues in the isPalindrome function :

  • the first while loop doesn't count the number of digits in the number, but counts one less.
  • as a result, the numArray array is too small (assuming that your compiler supports creating the array like that to begin with)
  • the for loop is writing a value past the end of the array, at best overwriting some other (possibly important) memory location.
  • the second while loop has no properly defined end condition - it can happily compare values past the bounds of the array.
  • due to that, the value in yes is potentially incorrect, and so the result of the function is too.
  • you return nothing if the function does not detect a palindrome.


//Determines if number is a palindrome
 bool isPalindrome(int num)   // Change this to bool
 {
      int n = num;
      int i = 0;
      int j = 0;
      int k = 0;
      int count = 1; // Start counting at 1, to account for 1 digit numbers
      int yes = 0;

  //Determines the size of numArray
  while(n/10 != 0)
  {
       // n%10; <-- What was that all about!
       count++;
       n = n/10;
  }

  int numArray[count];

  //Fill numArray with each digit of num
  for(i = 0; i < count; i++)                 // This will crash if you use index=count; Array indices go from 0 to Size-1
  { 
       numArray[i] = num%10;
       //printf("%d\n", numArray[i]);  
       num = num/10;
  }

  //Determines if num is a Palindrome
  /*     
  while(numArray[k] == numArray[count-1])       // Again count-1 not count; This is really bad though what if you have 111111 or some number longer than 6. It might also go out of bounds
 {
       k = k + 1;
       count = count - 1;  
       yes++;
  }
  */

  for(k = 1; k <= count; k++)
  {
     if(numArray[k-1] != numArray[count-k])
       return false;
  }

  return true;

}//End of Function

That's all I could find.

You also need to change this

if(isPalindrome(result) == 0)

To

if(isPalindrome(result))

The Code's Output after making the modifications: Link


The correct printf is the one after the for,after you iterate through all possible values

You are using int to store the value of the palidrome but your result is bigger then 65536, you should use unsigned

result = i * j;

this pice of code is wrong :

while(n/10 != 0) {
   n%10;
   count++;
   n = n/10;
}

it should be:

while(n != 0) {
  count++;
  n = n/10;
}

As well as the changes that P.R sugested.

You could do something like this to find out if the number is palindrome:

int isPalindrom(unsigned nr) {

    int i, len;
    char str[10];

    //convert number to string
    sprintf(str, "%d", nr);
    len  = strlen(str);

    //compare first half of the digits with the second half
    // stop if you find two digits which are not equal
    for(i = 0; i < len / 2  && str[i] == str[len - i - 1]; i++);

    return i == len / 2;
}


I converted the number to String so I'd be able to go over the number as a char array:

private static boolean isPalindrom(long num) {
    String numAsStr = String.valueOf(num);
    char[] charArray = numAsStr.toCharArray();
    int length = charArray.length;
    for (int i = 0 ; i < length/2 ; ++i) {
        if (charArray[i] != charArray[length - 1 - i]) return false;
    }
    return true;
}


I got correct answer for the problem, but I want to know is my coding style is good or bad from my solution. I need to know how can I improve my coding,if it is bad and more generic way.

#include<stdio.h>
#define MAX 999
#define START 100

int main()
{
    int i,j,current,n,prev = 0;
    for(i = START;i<=MAX;i++)
    {
        for(j=START;j<=MAX;j++)
        {
            current = j * i;
            if(current > prev)  /*check the current value so that if it is less need not go further*/
            {
                n = palindrome(current);
                if (n == 1)
                {
                    printf("The palindrome number is : %d\n",current);
                    prev = current;  // previous value is updated if this the best possible value.
                }
            }
        }
    }
}

int palindrome(int num)
{
    int a[6],temp;
    temp = num;
    /*We need a array to store each element*/
    a[5] = temp % 10;       
    a[4] = (temp/10) %10;
    a[3] = (temp/100) %10;
    a[2] = (temp/1000) %10;
    a[1] = (temp/10000) %10;
    if(temp/100000 == 0)
    {
        a[0] = 0;
        if(a[1] == a[5] && a[2] == a[4])
            return 1;
    }
    else
    {
        a[0] = (temp/100000) %10;
        if(a[0] == a[5] && a[1] == a[4] && a[2] == a[3])
            return 1;
        else
            return 0;
    }
}


No, the largest should be: 906609. Here is my program:

def reverse_function(x):
    return x[::-1]
def palindrome():
    largest_num = max(i * x
        for i in range(100, 1000)
        for x in range(100, 1000)
        if str(i * x) == reverse_function(str(i * x)))
    return str(largest_num)

print(palindrome())
0

精彩评论

暂无评论...
验证码 换一张
取 消