I'm trying to solve the problem given in Project Euler #4:
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.
There aren't any compilation errors in my solution...but program doesn't provide the correct output. I think I have made some mistake in defining boolean function.
Any ideas?
#include <iostream>
#include <math.h>
using namespace std;
bool isPalindrome(int z) {
// store z in t to compare it later with its reversed number
int t = z;
int rev = 0;
// This while loop reverses the number
while (z > 0) {
int dig = z % 10;
rev = rev * 10 + dig;
z = z / 10;
}
if (t == rev)
return true;
else
return false;
}
void palindrome(int k) {
int b = 0;
int a = pow(10, k);
// calculate product of two numbers
// replace it if it's palindrome and greater than previously stored value b
// for loop to calculate product of all 3 (in general k) digit numbers
for (int i = pow(10,k-1); i = pow (10,k) - 2; i++) {
for (int j = i; j = pow (10,k) - 2; j++) {
int c = i * j;
if (isPalindrome(c) && c > b) {
b = c;
}
}
}
cout << "Largest Palindrome = " << b << endl;
}
int main() {
int n;
cout << "Enter the digit length" <<"\t";
cin >> n;
palindrome(n);
return 0;
}
For an example of it not working, I tried inputting n=3 and it just hangs, with no output. What am I doing wrong?
It seems to me that your problem is in the line,
for (int i = pow(10,k-1); i = pow (10,k) - 2; i++) {
Consider how your loop is going to terminate.