Boom_mooB
Boom_mooB

Reputation: 97

why does my code continue to crash at run-time?

This is my code for project euler problem number 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.

However, my code won't compile on Visual C++. It keeps saying "Access Violation." So can someone tell me why my code doesn't work? And if my code does work on your compiler, does it give the right answer?

#include <iostream>
#include <cmath>
int isitapalindrome(int num);

int main (void) 
{
bool pali = false;
int a, b, c, d, e = 0;
for (a = 999; a > 100; a-- ) 
{
    for (b = 999; b > 100; b--) 
    {
        c = a*b;
        pali = isitapalindrome(c);
        if (pali == true) 
        {           
            c > e? c: e;                            
            d = c;                                  
            e = c;
        }
        else continue;
    }
}
std::cout<<d<<std::endl;
system ("pause");
return 0;
}

int isitapalindrome (int num) 
{
bool isit = false;
int digits[8];
int test = num;
int i, j, palindrome = 0;

for (i = 0; test >= 0; i++) 
{           
    digits[i] = test%10;            
    test = (test -  test%10)/10;    
}
for (j = 0; i>=j; j++) 
{
    palindrome += digits[j] * 10^(i-j);
}

if(palindrome = test) 
{
    isit = true; 
}
return isit;
}

Upvotes: 0

Views: 97

Answers (1)

Daniel Fischer
Daniel Fischer

Reputation: 183888

This

for (i = 0; test >= 0; i++)

is an infinite loop because

test = (test -  test%10)/10;

will never make test negative. Replace the loop condition with test > 0.

Upvotes: 1

Related Questions