Hello!
I am working on Euler Project exercise number 17. Here is the problem from the website.
"If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?"
Here is my code:
Code:
#include <stdio.h>
#include <string.h>
#define LENGTHOFHUNDRED 7
#define LENGTHOFONETHOUSAND 11
#define NUMSTART 1
#define NUMEND 1000
#define ANDLENGTH 3
static char * base_digits[] = { "one" , "two" , "three" , "four" , "five" , "six" , "seven" , "eight" , "nine" };
static char * teens[] = { "eleven" , "twelve" , "thirteen" , "fourteen" , "fifteen" , "sixteen" , "seventeen" , "eighteen" , "nineteen" };
static char * mults_of_ten[] = { "ten" , "twenty" , "thirty" , "forty" , "fifty" , "sixty" , "seventy" , "eighty" , "ninety" };
unsigned int count_letters( unsigned int );
int main(){
unsigned int count = 0 , i;
for( i = NUMSTART; i <= NUMEND; i++ )
count += count_letters( i );
printf( "total letters-> %d\n" , count );
return 0;
}
unsigned int count_letters( unsigned int num ){
if( num < 20 && num > 10 )
return strlen( teens[ num - 11 ] );
if( num == 1000 )
return LENGTHOFONETHOUSAND;
unsigned int digitcount = 0 , n , mdivisor = 1;
if( num > 100 && ( num % 100 ) )
digitcount += ANDLENGTH;
do{
num -= ( n = num % ( mdivisor *= 10 ) );
if( n ){
if( n < 10 )
digitcount += strlen( base_digits[ n - 1 ] );
else if( n < 100 )
digitcount += strlen( mults_of_ten[ ( n / 10 - 1 ) ] );
else
digitcount += strlen( base_digits[ ( n / 100 - 1 ) ] ) + LENGTHOFHUNDRED;
}
}while( num );
return digitcount;
}
Can someone show me where my logic went awry?