C++ palindrome

I have implemented a code to find the largest palindrome made from the product of two 3-digit numbers. However, I'm not able to get it right somehow. My answer is quite off: 998001. Unable to find out whats wrong with my code..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <vector>
#include <math.h> 
void checkpalindrome(std::vector<int> vect, int k, int* count, int size)
{
	*count = 0;
	while ((size - 1) / 2 != 0)
	{
		if (vect[k] == vect[size - 1])
		{
			k++;
			size--;
			(*count)++;
		}
		else
		{
			break;
		}
	}
  }
int main()
{
	int k = 0, sum = 0, n = 0, size = 6, temp=0, count = 0, max=0;
	std::vector<int>vect(6);
	for (size_t i{ 100 }; i <= 999; i++)
	{
		for (size_t j{ 100 }; j <= 999; j++)
		{
			sum =i* j;
			while(k<6)
			{
				temp = sum;
				n = temp % 10;
				temp /= 10;
				vect.at(k)= n;
				k++;

			}
			k = 0;
			temp = 0;

			checkpalindrome(vect, k, &count, size);
				
 			if (max < sum)
			{
				if ((count - 1) == 3)
				{
					max = sum;
				}
				else
				{
					continue;
				}
 				
			}

		}
		

	}
	std::cout << max;
}
> sum =i* j;
Calling a product a sum is confusing.

> while(k<6)
Why isn't this a for loop, or better yet - a function.

> checkpalindrome(vect, k, &count, size);
Why not return a count, instead of passing a pointer (why not a reference?)

Learn how to use your debugger.
Seriously, you don't just stare at code and try to mentally deduce the problem.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
$ g++ -std=c++11 -g foo.cpp
$ gdb -q ./a.out
Reading symbols from ./a.out...done.
(gdb) b checkpalindrome(std::vector<int, std::allocator<int> >, int, int*, int) 
Breakpoint 1 at 0x400a7d: file foo.cpp, line 6.
(gdb) run
Starting program: ./a.out 

Breakpoint 1, checkpalindrome (vect=std::vector of length 6, capacity 6 = {...}, k=0, count=0x7fffffffdde4, size=6) at foo.cpp:6
6		*count = 0;
(gdb) p vect
$1 = std::vector of length 6, capacity 6 = {0, 0, 0, 0, 0, 0}
(gdb) bt
#0  checkpalindrome (vect=std::vector of length 6, capacity 6 = {...}, k=0, count=0x7fffffffdde4, size=6) at foo.cpp:6
#1  0x0000000000400c44 in main () at foo.cpp:42
(gdb) up
#1  0x0000000000400c44 in main () at foo.cpp:42
42				checkpalindrome(vect, k, &count, size);
(gdb) p i
$2 = 100
(gdb) p j
$3 = 100
(gdb) p sum
$4 = 10000
(gdb) p vect
$5 = std::vector of length 6, capacity 6 = {0, 0, 0, 0, 0, 0}
(gdb) 

It's already broken at the first test.
Last edited on
Topic archived. No new replies allowed.