here is the finished article
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int AddStrings( char *Numx, char *Numy, char *Result )
{
//it is assumed that numx and numy have the same number of digits
int Answer = 0;
for ( int i = strlen( Numx ) - 1; i >= 0; i-- )
{
int x = Numx[i] - '0';
int y = Numy[i] - '0';
Answer += x + y;
Result[i] = Answer % 10 + '0';
Answer /= 10;
}
return Answer;
}
void PrependString( char *strPrePend, int x )
{
for ( int i = strlen( aaaaaaaaaaaaaaaaaaaaaaaaaaa ) - 1; i >= 0; i-- )
strPrePend[i + 1] = strPrePend[i];
strPrePend[0] = x + '0';
}
void ReverseString( char *Source, char *Result )
{
for ( int j = strlen( Source ) - 1, i = 0; i < strlen( Source ); i++, j-- )
Result[j] = Source[i];
}
int isPalindrome( char *Number )
{
if ( Number[strlen( Number ) - 1] == '0' ) return 0;
for ( int j = strlen( Number ) - 1, i = 0; i <= strlen( Number ) / 2; i++, j-- )
if ( Number[i] != Number[j] ) return 0;
return 1;
}
int main()
{
int LychrelNum = 0;
for ( int i = 10; i < 10000; i++ )
{
char strNum[32] = { '\0' }, strResult[32] = { '\0' }, strReversed[32] = { '\0' };
sprintf( strNum, "%d", i );
ReverseString( strNum, strReversed );
int Carry = AddStrings( strNum, strReversed, strResult );
if ( Carry )
PrependString( strResult, Carry );
int Loopcnt = 1;
while ( !isPalindrome( strResult ) && Loopcnt < 50 )
{
if ( strlen( strResult ) > 30 ) // check the next iteration will fit with poss carry
{
printf("array overflow detected\n");
exit(1);
}
strcpy( strNum, strResult );
ReverseString( strNum, strReversed );
Carry = AddStrings( strNum, strReversed, strResult );
if ( Carry )
PrependString( strResult, Carry );
Loopcnt++;
}
if ( Loopcnt >= 50 ) LychrelNum++;
}
printf("%d\n", LychrelNum);
return 0;
}
I have a memory management question. in my for loop in main i declare three char arrays as they are with in the loop i believe they exist with in the scope of the curly brackets. if this is the case does it create multiple copies of each variable or do they loose scope when the for loop iterates?