Hey I am working on http://projecteuler.net/problem=4 and this is the program I have I don't know why its not working! Please help, looks like it is in an infinite loop for some reason...
int main()
{
long a, b;
long biggest = 0;
a = 999;
b = 999;
bool trueistrue = 1;
for(;a != 0 && b != 0;)
{
long num, rem,numCopy;
long sum = 0;
numCopy = a * b;
num = a * b;
while(num!=0)
{
rem=num%10;
num=num/10;
sum=sum*10+rem;
}
if(numCopy == num)
{
if(biggest < num)
biggest = num;
}
if(trueistrue)
b = b - 1;
else
a = a - 1;
if(b == 0)
{
trueistrue = 0;
b = a - 1;
a = 999;
}
if(a == 0)
{
trueistrue = 1;
a = b - 1;
b = 999;
}
}
cout << biggest << " is the answer a = " << a << " b = " << b;
cin.get();
cin.get();
return 0;
}
int main()
{
long a, b;
long biggest = 1;
a = 999;
b = 999;
bool trueistrue = 1;
for(;a != 0 || b != 0;)
{
if(b == 1 && a == 2)
break;
long num, rem,numCopy;
long sum = 0;
numCopy = a * b;
num = a * b;
while(num!=0)
{
rem=num%10;
num=num/10;
sum=sum*10+rem;
}
if(a * b == num)
{
if(biggest < a * b)
biggest = a * b;
}
if(trueistrue)
b = b - 1;
else
a = a - 1;
if(b == 0)
{
trueistrue = 0;
b = a - 1;
a = 999;
}
if(a == 0)
{
trueistrue = 1;
a = b - 1;
b = 999;
}
}
cout << biggest << " is the answer a = " << a << " b = " << b;
cin.get();
cin.get();
return 0;
}
The problem now is that biggest doesn't change from its original value. I don't know why, that is what I am wondering about, I don't need anyone to write my program just tell me why biggest doesn't change. As for what the thing I am making is you can click that link in my original post...
a. For positive a and b, a*b is greater than a*(b-1), a*(b-2) etc., we can omit those checks.
b. 789 * 687 == 687 * 789, we need not check both
c. The check for a number being a palindrome is far more expensive than the check if a number is greater than another number. We can place the inexpensive check first.
Stick to the the idea that bool variables are either true or false - then re-evaluate this piece of code to come to an inescapable conclusion.
With use of this variable in this code:
1 2 3
if(a == 0)
{
trueistrue = 1;
This translates to: if a is false, then trueistrue is true. A lesson in nightmare confusion. lol
1 2 3 4 5 6 7 8 9 10 11
if(a == 0)
//can be written
if(!a) {} // if not a, in other words if a equals false
//can also do this
if (a) // is variable a true?
bool Quit = false;
//user wants to quit
Quit = true;
With this:
for(;a != 0 || b != 0;) {}
We have for(initialise none; end-condition; increment none) {}
A while loop looks like this while(end-condition){} Do you see my point here?
I hope this has cleared up some concepts for you, good luck with your coding, and have fun !!
Thanks for the lesson, I didn't understand very much of that but atleast I got the program to work and I understand the algorythm decently. The reason I called it trueistrue is just because it is so fun to make trueistrue false :P But I made the program overly complicated and stupid in the first few posts...