Project Euler with C++ - compiler won't process after 100 x 101
I've started working with C++ and was fiddling around with some problems on projecteuler.net.
I'm on question #4 and here's my code:
algorithm to check whether the number is a palindrome:
bool forwardCheck(long posPal){
long n = posPal;
long rev = 0;
long dig;
while (posPal > 0){
dig = posPal % 10;
rev = rev * 10 + dig;
posPal = posPal % 10;
}
return n == rev;
}
main program:
int main(){
long palindrome;
cout << "We are finding the largest palindrome made from two 3-digit numbers.\n"
<< "Calculating...\nCalculating..开发者_Go百科.\nDone!\n";
for (long i = 100; i < 1000; i++){
for (long j = 100; j < 1000; j++){
long mult = i * j;
if (forwardCheck(mult)){
palindrome = mult;
//testing function above
cout << mult << " is a palindrome!\n";
} else
//testing function above
cout << mult << " is not a palindrome...\n";
}
}
cout << "The largest palindrome composed of two 3 digit numbers is: " << palindrome
<< endl;
return 0;
}
I'm using X11 on OS X as my compiler with g++ and my problem is that, using the code above, the numbers get to 101,000 as the multiple and then stops and stalls after that. My question is:
Why is it doing this? Am I approaching this inefficiently?
I realize that an alternative is to start from long = 999 and iterate downwards but I've coded but it gets stuck after the "Done!" statement (yes, I know it's a bit ambitious to program that in before the algorithm has run but I like to be optimistic. :)
By stuck and stalls, I mean that the CPU usage spikes but nothing is written to the console.
As a general side note:
Is there a way I can debug through the console, i.e. have it tell me what it's doing similar to echo in windows command prompt? I'm new to OS X too...
Have a look at this code:
while (posPal > 0){
dig = posPal % 10;
rev = rev * 10 + dig;
posPal = posPal % 10;
}
I think you are miscalculating posPal
at the bottom of the loop.
Try replacing with posPal = posPal / 10
.
seems that it should be
posPal = posPal / 10
e.g. starting with 123 you want to use 3 for building an inverse number and to move to 12
精彩评论