Question

Hello everyone! Having solved my other question I came out with a new problem. I am doing an exercise which i need to find the largest palindrome made from the product of two 3-digit numbers. I made it but i output all the 3-digit products. Is there a way only to output the max one? I have been searching and I found a possible solution by doing the abs of the differences, would that work for my code? I do not want a code as answer if that's possible, maybe some hint and tips so i can struggle a bit and get my objective, here is the 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
  /*A palindromic number reads the same both ways. The largest palindrome made from the product of 
two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.*/
#include <iostream>

using namespace std;
bool esPal(int z);
int main(){
	int resultado = 0;
	for (int i = 100; i < 999; i++)
	{
		for (int j = i; j < 999; j++)
		{
			resultado = i * j;
			if (esPal(resultado))
			{
				cout << "Found: " << resultado << " multiplicando " << i << " x " << j << endl;
			}
		}

	}
	system("PAUSE");
}

bool esPal(int z)
{
	int t = z;
	int rev = 0;

	// reverse
	while (z > 0)
	{
		int dig = z % 10;
		rev = rev * 10 + dig;
		z = z / 10;
	}
	if (t == rev)
		return true;
	else
		return false;
}


Thank you very much in advance!
Remember the maximum calculated palindrome. Initially its 0. As soon as you've found a new palindrome do compare it with the current maximum. If its greater than set maximum to the new value. Don't forget remembering also i and j. Finally output the result after the loop.



EDIT: Syntax error.
Last edited on
Thank you very much! I am going to try it, makes a lot of sense.

Delsh

EDIT: Worked, thanks! Here is the 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
/*A palindromic number reads the same both ways. The largest palindrome made from the product of 
two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.*/
#include <iostream>

using namespace std;
bool esPal(int z);
int main(){
	int resultado = 0;
	int max = 0;
	for (int i = 100; i < 999; i++)
	{
		for (int j = i; j < 999; j++)
		{
			resultado = i * j;
			if (esPal(resultado))
			{
				if (resultado > max)
				{
					max = resultado;
				}
			}
		}

	}
	cout << max << endl;
	system("PAUSE");
}

bool esPal(int z)
{
	int t = z;
	int rev = 0;

	// reverse
	while (z > 0)
	{
		int dig = z % 10;
		rev = rev * 10 + dig;
		z = z / 10;
	}
	if (t == rev)
		return true;
	else
		return false;
}
Last edited on
Topic archived. No new replies allowed.