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.
Hi, I have been trying to solve project euler #4 for a bit now and I keep getting stuck. I don't know C++ very well and I just started learning a few weeks ago off and on. If somebody could show me how to complete this I would be very happy. If you are going to post please to to include comments that explain what you are doing.
What I have so far is pretty basic and missing the major parts, I really only have the code to reverse the number.
I need simple code to do this, and I get confused easily. If you are willing to work me through this I would appreciate it.
#include <iostream>
usingnamespace std;
int main(){
int Num = 0; //what the number is to reverse
int reverseNum = 0;
while(Num > 0){ //to reverse the number
reverseNum *= 10;
reverseNum += (Num % 10);
Num /= 10;
}
cout << "The reverse number is: " << reverseNum << endl; //display the reversed number
return 0;
}
I have been messing around with the loops and don't really get how to test my original against my new number and how to go back through the loop if it is false or if it is true to display the cout line.
I don't know enough to try to write the code, but I know the general idea. (You can google palindromes and get the code to find the two numbers between 101 and 999 that multiply to the largest palindrome.)
The main thing is that after your calculations, you have to test the numbers by converting them to strings and seeing if stringForward == stringBackward. But I'm just now learning about strings on the fly to complete another program, so I can't help you there.
#include <iostream>
#include <sstream>
usingnamespace std; //learn to avoid this... for now, not a big deal
//iterate through a string to check if it's a palindrome
bool is_palin(const string &s)
{
for(int i=0, j=s.size()-1; i<j; i++, j--)
if(s[i]!=s[j]) returnfalse;
returntrue;
}
//convert a number to a string using a stringstream
string to_string(constint &conv)
{
stringstream ss;
ss << conv;
return ss.str();
}
int main()
{
int palin=0;
int l_val=0;
int r_val=0;
int less_than_min=99;
int max=999;
//multiply the numbers starting @ 999, moving backwards to 100
for(int i=max; i>less_than_min; i--) {
for(int j=i; j>less_than_min; j--) {
int k=i*j;
if(k<=palin) break; //really speeds things up
//convert to a string and check if it's a palindrome
if(is_palin(to_string(k))) {
palin=k;
l_val=i;
r_val=j;
}
}
}
cout << "Largest palindrome: " << palin << " (" << l_val << "*" << r_val << ")";
cin.get(); //so you can see the results--press ENTER to exit
return 0;
}
Thanks! that code looks great, I just don't understand how the bool check to see if it is the same forward and backward. Could someone go into more detail on that?