Palindromic numbers problem

This is a discussion on Palindromic numbers problem within the C Programming forums, part of the General Programming Boards category; I wrote a program to find the largest palindromic number one could produce as the product of two three digit ...

  1. #1
    Registered User
    Join Date
    Aug 2011
    Posts
    24

    Palindromic numbers problem

    I wrote a program to find the largest palindromic number one could produce as the product of two three digit numbers.

    Code:
    int main (void)
    {
    	int i, j, z;
    	int num;
    	char buf[6];
    	char test[6];
    
    	for(i=100; i<=999; i++)
    	{
    		for(j=100; j<=999; j++)
    		{
    			num = i * j;
    
    			sprintf(buf, "%d", num);
    
    			for(z=0; z<=6; z++)
    				test[z]=buf[z];
    			
    			int len=strlen(buf);
    
    			for(z=0; z<len/2;z++)
    			{
    				test[z]^=test[len-z-1];
    				test[len-z-1]^=test[z];
    				test[z]^=test[len-z-1];
    			}
    
    			/*puts(buf);*/
    			/*puts(test);*/
    			/*printf("\n");*/
    			if(test == buf)
    				puts(buf);
    
    		}
    	}
    
    	return 0;
    }
    I'm having problems withe the
    Code:
    if(test == buf)
    part. I know the program produces the correct answer (906609), but when I run it, nothing ever ends up being printed. Should I be comparing the two arrays differently?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,893
    This accesses the arrays out of bounds because of the use of <= instead of < :
    Code:
    for(z=0; z<=6; z++)
        test[z]=buf[z];
    Actually, you have another problem. 999 * 999 = 998001, which when converted to a numeric string would require 6+1=7 characters, so your arrays are not big enough.

    Also:
    Code:
    test[z]^=test[len-z-1];
    test[len-z-1]^=test[z];
    test[z]^=test[len-z-1];
    Use a conventional swap involving a "temporary" variable instead.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Numbers to text problem
    By d2rover in forum C# Programming
    Replies: 2
    Last Post: 01-30-2011, 09:39 AM
  2. Undefined Behaviour (Palindromic Number Finder)
    By pobri19 in forum C++ Programming
    Replies: 12
    Last Post: 09-28-2008, 04:54 AM
  3. checking if binary numbers are palindromic
    By Beatz in forum C Programming
    Replies: 3
    Last Post: 01-24-2008, 12:49 PM
  4. Random numbers problem
    By ManiacBR in forum C++ Programming
    Replies: 4
    Last Post: 11-09-2006, 11:34 AM
  5. problem with random numbers
    By xxwerdxx in forum C Programming
    Replies: 2
    Last Post: 11-24-2005, 07:56 AM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21